Class 方法调用实例方法成功

Class method successfully called instance method

我所知道的关于编程的一切都说实例方法可以调用 class 方法,但是 class 方法 不能 调用实例方法。

这个post同意... Call instance method from class method

然而奇迹般的是 class 方法 sharedInstance 设法调用了实例方法 init。我错过了什么??

static iRpDatabase *sharedDatabase;

@implementation iRpDatabase
{ 
}

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

    // this is an instance method, called from class method above.
    -(id)init
    {
        if (self = [super init]) {
            someInstanceVariable = XYZ;
            [self someInstanceMethod];
        }
        return self;
    }

声明class方法不能调用实例方法意味着class方法不能调用self上的实例方法,因为self表示class,不是 class.

的实例

sharedInstance 方法中,您正在调用实例方法,但它是在 class 的特定实例上调用的。没关系。

想想这个例子:

+ (void)someClassMethodOfiRpDatabase {
    NSString *str = @"Hello";
    NSInteger len = [str length]; // look - I called an instance method
}

此示例与您的 sharedInstance 方法问题没有什么不同。可以在对象的特定实例上调用实例方法,即使您碰巧在某些 class 方法中。