Re: Is ther a conventional way to allocate and initialize an object in Objective-C?
Re: Is ther a conventional way to allocate and initialize an object in Objective-C?
- Subject: Re: Is ther a conventional way to allocate and initialize an object in Objective-C?
- From: Gregory Weston <email@hidden>
- Date: Sun, 19 Aug 2007 07:33:37 -0400
Bob Ueland wrote:
What I'm wondering about is the way Kochan allocates and
initializes the the address book. I have two questions:
1. Is this the conventional way to initialize an object. I was
expecting in the main program something like
AddressBook *myBook = [[AddressBook alloc] init];
NSString *addressBookName = @"Linda's Address Book";
[AddressBook setName:addressBookName];
[AddressBook setBook];
where setName and setBook would be used insted of initWithName.
What you expected would not be common. That last line in particular
would be rather strange both for behavior and for the name chosen if
that name did exist. I think you'll find it a common idiom that the
author of a class will provide one or more initializers that take a
sufficient set of arguments to create a fully set up (immediately
usable) object. There's no reason client code should have to know
what it takes to achieve that, let alone explicitly do so.
2. Why does Kochan use the test
if (self) {
in the initWithName method. I mean if self does not exist the
method initWithName would never be called, would it?
Sure it would. initWithName: is gong to be sent to whatever object
alloc returned, even if that object is nil. Or, looking at the line
above it, the superclass' init method may return nil (which is why,
btw, it was important to assign the result of init back to self).
_______________________________________________
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