Objective c 类方法ios的作用是什么;“自我”;提到

Objective c 类方法ios的作用是什么;“自我”;提到,objective-c,singleton,Objective C,Singleton,当我调用+sharedInstance时,self指的是什么?如何允许我从类方法调用init?self是类 #import "ApiService.h" @implementation ApiService static ApiService *sharedInstance = nil; + (ApiService *)sharedInstance { if (sharedInstance == nil) { sharedInstance = [[self

当我调用
+sharedInstance
时,self指的是什么?如何允许我从类方法调用init?

self
是类

#import "ApiService.h"

@implementation ApiService
static ApiService *sharedInstance = nil;

+ (ApiService *)sharedInstance
{
    if (sharedInstance == nil)
    {
        sharedInstance =  [[self alloc]init];
    }

    return sharedInstance;
}

- (id)init
{
    if (self = [super init])
    {
    }
    return self;
}
@end
同:

+ (id)create {
  return [[self alloc] init];
}
或者在你的例子中:

+ (id)create {
  return [[SomeClass alloc] init];
}

这允许您从类方法调用
self
上的类方法。它允许您在继承时在子类上调用它们,因为类方法也是继承的。

检查这个问题,以获得一个更好的生成单例的方法:如果self是类,那么当您执行诸如self.property之类的操作时,该类怎么可能是单例呢?除非属性是静态的?@Rob,objective-c中确实有2个self,请检查或更好的措辞:类本身就是对象,因此它们可以通过
self
向自己发送消息。看看这个链接,奇怪的是,在C++或java中,你肯定不会使用这个术语,例如,这不是类……它有实际的理由使用自我类的方法。在继承场景中,使用“self”而不是“ApiService”将保证ApiService的子类不必重写“sharedInstance”方法,并且能够正确地获取子类对象。这个技巧实际上在苹果的编程指南中提到过。在最底层,提示:不要在类工厂方法中使用[[XYZPerson alloc]init],而是尝试使用[[self alloc]init]。
+ (ApiService *)sharedInstance
{
    if (sharedInstance == nil)
    {
        sharedInstance =  [[ApiService alloc]init];
    }

    return sharedInstance;
}