0

Everything I know about programming says that instance methods can call class methods, but class methods cannot call instance methods.

This post agrees... Call instance method from class method

Yet miraculously the class method sharedInstance manages to call instance method init. What am I missing ??

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;
    }
Community
  • 1
  • 1
Logicsaurus Rex
  • 3,172
  • 2
  • 18
  • 27

1 Answers1

1

The statement that a class method can't call instance methods means that the class method can't call instance methods on self since self represents the class, not an instance of the class.

In the sharedInstance method you are calling an instance method but it is being called on a specific instance of the class. That's fine.

Think of this example:

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

This example in no different than your sharedInstance method question. It's fine to call instance methods on a specific instance of an object, even if you happen to be in some class method.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • If you look at your example (which we can see on any subclass of NSObject) you'll see that you are not calling init on self but on the result of [self alloc] -which is an instance. Best – Jef Feb 07 '16 at 00:22
  • @Jef You should post your comment to the question, not this answer. – rmaddy Feb 07 '16 at 00:24