@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.
When you refer to
selfin class method,selfrefers to the class, itself, not to a particular instance of that class. By usingselfrather 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 theselfreferences 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:
And consider this subclass:
Then consider code that does:
The problem is that the
objectfactory method will return aBaseClassObjectrather than aSubClassObject. But that is remedied if we alter the definition of that factory class method to useself:Now when I refer to
[SubClassObject object], I'll get an instance ofSubClassObjectrather thanBaseClassObject.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
selfin 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.