how to create an object using self?
I thought I understood the use of self while referring to anything in the current class. After encountering this warning and subsequent run failure, I have googled many variants of "define self" or "usage of self" and gotten nowhere. This problem is how to create an object without the warning, and understand why.
#import <Cocoa/Cocoa.h>
@interface Foo : NSObject {
Foo *obj;
}
-(void)beta;
@end
#import "Foo.h"
@implementation Foo
-(void)beta{
obj = [self new]; // 'Foo' may not respond to '-new'
}
@end
Note, if I substitute Foo
for self
, there's no problem. I thought the class name and self were equivalent, but obviously the compiler doesn't think so.
Perhaps an explanation of what's wrong here will not only solve my problem but also enlighten my understanding of the usage of
self
. 开发者_JAVA百科
Are there any tutorials about proper usage of self? I couldn't find anything beyond something like "
self
is the receiver of the message," which didn't help me at all.
self
references the receiver of a message, so in this specific case, self
references the object on which -beta
was invoked. (Within the scope of a class method, self
references the class' Class
object)
Now, since self
in this case references the object that the method was invoked on, the compiler gives you a warning because new
is not an instance method of Foo
. new
is a class method inherited from NSObject
. So, the correct way to do this would be to retrieve the Class
object from self
, then invoke new
on that:
- (void) beta {
obj = [[self class] new];
}
精彩评论