bames53":2w3syw6c said:
I'd guess that it refers to the class. So you might do [[self alloc] init] in a class factory method or something.
This is correct. In a class method, self is used to access class methods of the class the method was called on.
Why would you use self rather than naming the class directly? To correctly handle inheritance:
Code:
@interface BaseClass : NSObject
+ (void)doStuff;
+ (void)method;
@end
@implementation BaseClass
+ (void)doStuff {
[self method];
}
+ (void)method {
NSLog(@"A");
}
@end
@interface SubClass : BaseClass
+ (void)method;
@end
@implementation SubClass {
+ (void)method {
NSLog(@"B");
}
So, if I call [BaseClass doStuff], it prints "A", and if I call [SubClass doStuff], it prints "B", like you'd expect it to do if you overloaded the method. If I did this in the Java style, where I don't have a reference to the class:
Code:
+ (void)doStuff {
[BaseClass method];
}
it would always print an "A", whether I called doStuff on BaseClass or SubClass.
This is a fundamental language difference; in Java, you can't override a static method at all, so you don't get a language construct to handle that case (a this pointer in a static method).