开发者

Will this work?

开发者 https://www.devze.com 2023-02-07 17:13 出处:网络
UILabel *testLbl = [[self alloc] init]; 开发者_开发技巧 This is where the confusion started: It’s usually better to use a variable other than self to refer to an instance inside a class
UILabel *testLbl = [[self alloc] init];
开发者_开发技巧

This is where the confusion started:

It’s usually better to use a variable other than self to refer to an instance inside a class method:

+ (id)rectangleOfColor:(NSColor *)color {
id newInstance = [[Rectangle alloc] init]; // GOOD [newInstance setColor:color]; return [newInstance autorelease];
}

In fact, rather than sending the alloc message to the class in a class method, it’s often better to send alloc to self. This way, if the class is subclassed, and the rectangleOfColor: message is received by a subclass, the instance returned will be the same type as the subclass (for example, the array method of NSArray is inherited by NSMutableArray).

+ (id)rectangleOfColor:(NSColor *)color {
id newInstance = [[self alloc] init]; // EXCELLENT [newInstance setColor:color]; return [newInstance autorelease];
}


No, It'll cause a "UILable undeclared (first use in this function)" error.


No, it won't work. In your first line, you are sending the alloc message to an instance of a class. In the examples you copied out of Apple's documentation, they are sending alloc messages to the Class Rectangle. The difference is that your line is (apparently) inside an instance method, Apple's examples are inside class methods. There is a difference.

Like @Denis mentioned, you can do what you're trying to do by saying [[[self class] alloc] init], but in practice, don't do this. You'll almost never need the flexibility this offers and it will only muddy the intent of the new object.

0

精彩评论

暂无评论...
验证码 换一张
取 消