类方法ios“self”指的是什么

时间:2013-01-28 16:30:13

标签: objective-c singleton

#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

当我打电话给+sharedInstance自我指的是什么?如何允许我从Class方法调用init?

1 个答案:

答案 0 :(得分:2)

self是班级。

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

与:

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

或者在你的例子中:

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

    return sharedInstance;
}

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

相关问题