1
votes
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];
}
2
means is there any difference between the two: UILabel *testLbl = [[self alloc] init]; UILabel *testLbl = [[UILabel alloc] init]; - Prabh
Are you running this in a UILabel instance method? then you could use [[[self class] alloc] init]; - Denis 'Alpheus' Cahuk

2 Answers

2
votes

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

1
votes

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.