Is ther a conventional way to allocate and initialize an object in Objective-C?
Is ther a conventional way to allocate and initialize an object in Objective-C?
- Subject: Is ther a conventional way to allocate and initialize an object in Objective-C?
- From: Bob Ueland <email@hidden>
- Date: Sun, 19 Aug 2007 03:18:11 -0700 (PDT)
I'm reading Kochan's book "Programming in Objective-C". In program 15.11 he creates an address book that is to be filled with address cards. (Address cards is a class we created earlier in the book, a simple class with just two fields name and email). I've snipped away everything except from the relevant parts in the code.
---------------- AddressBook.h, interface file ----------
#import <Foundation/NSArray.h>
#import "AddressCard.h"
@interface AddressBook: NSObject
{
NSString *bookName;
NSMutableArray *book;
}
-(AddressBook *) initWithName: (NSString *) name;
...
@end
---------------- AddressBook.m, implementation file ----------
#import "AddressBook.h"
@implementation AddressBook;
-(id) initWithName: (NSString *) name
{
self = [super init];
if (self) {
bookName = [[NSString alloc] initWithString: name];
book = [[NSMutableArray alloc] init];
}
return self;
}
...
@end
------------ main program --------------------
#import "AddressBook.h"
#import <Foundation/NSAutoreleasePool.h>
int main (int argc, char *argv[])
{
...
AddressBook *myBook = [AddressBook alloc];
...
myBook = [myBook initWithName: @"Linda's Address Book"];
...
return 0;
}
----------------------------------------
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.
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?
Thanks Bob
____________________________________________________________________________________
Got a little couch potato?
Check out fun summer activities for kids.
http://search.yahoo.com/search?fr=oni_on_mail&p=summer+activities+for+kids&cs=bz
_______________________________________________
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