Re: initializer methods
Re: initializer methods
- Subject: Re: initializer methods
- From: Roland King <email@hidden>
- Date: Fri, 20 Nov 2009 12:31:56 +0800
Lynn Barton wrote:
After many years of using procedural programming languages, I am trying to learn Cocoa. Today I am reading the Apple document "The Objective-C Programming Language" dated 2009-10-19. On page 46 I read the following:
This is an example of what not to do:
+ (Rectangle *)rectangleOfColor:(NSColor *) color
{
self = [[Rectangle alloc] init]; // BAD
[self setColor:color];
return [self autorelease];
}
However, on page 49 I read the following:
There are several constraints and conventions that apply to initializer methods that do not apply to other methods:
.
.
.
• You should assign self to the value returned by the initializer.
This is because the initializer could return a different object than the original receiver.
Could someone please explain this apparent contradiction?
Because the first method isn't an initializer method, it's a Class
method, a convenience method for returning another object.
initializers are the instance methods which conventionally start with
init (look a bit back from where you were on page 49) and those methods
should assign to self because self in that case means the object you are
initializing (and returning).
For class methods, self is the class, in that example at the top you're
not returning the class or a class object, you want to return an object
OF the class, so self is just the wrong thing to use.
Remember that a '+' at the start of a method signature denotes a class
method, a '-' at the start of a method signature denotes an instance
method.
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden