self concept ,if i use self in class method not in instance method

129 views Asked by At
@interface hello:SKScene
@end

@implementation hello

+(void)method{

    [self here];

}
@end

main.m

[hello method];

here,when i call this class method without allocating memory for object then method self,belong to whom???? my question is self belong to class that contain the method calling on then because i did not define object then ,why i still can use self on this?????

is it still belong to class on which it calling ??please give me proper concept of self on instance method and class method.

2

There are 2 answers

4
Rob On BEST ANSWER

When you refer to self in class method, self refers to the class, itself, not to a particular instance of that class. By using self rather than the actual class name in these class methods, it makes it easier to subclass the class in question. Specifically, the class method will be inherited, but the self references will now refer to the subclass rather than the base class. If you refered to the base class by name, this would not be true.

Consider this factory method:

@implementation BaseClassObject

// THIS IS WRONG 

+ (BaseClassObject *)object {
    return [[BaseClassObject alloc] init];
}

@end

And consider this subclass:

@interface SubClassObject : BaseClassObject
@end

Then consider code that does:

SubClassObject *object = [SubClassObject object];  // WRONG

The problem is that the object factory method will return a BaseClassObject rather than a SubClassObject. But that is remedied if we alter the definition of that factory class method to use self:

@implementation BaseClassObject

// THIS IS RIGHT 

+ (instancetype)object {
    return [[self alloc] init];
}

@end

Now when I refer to [SubClassObject object], I'll get an instance of SubClassObject rather than BaseClassObject.


Note: In my contrived example, it's rather important to use self. You may, though, encounter code where it does not appear to be immediately relevant (for example, you might have a base class, but no subclass at this time).

Even in this case, you probably should be in the habit of using self in these class methods, regardless, to "future-proof" your code, so that if you ever subclass this base class at some unforeseen date in the future, these class methods are more likely to function properly even when subclassed.

0
Ken Thomases On

Just to add a little to Rob's answer: the class object is created automatically by the compiler and/or Objective-C runtime. (It doesn't matter to you which it is.) For all intents and purposes, it's permanent. There's no need for it to be managed.