There are two choices for constructors in Objective C/Cocoa:
1. Class Constructor
Product *product = [Product productWithIdentifier:@"Chocolate"];
// Use product
2. Alloc/init Constructor
Product *product = [[Product alloc] initWithIdentifier:@"Chocolate"];
// Use product
[product release];
What I do
- I tend to use the class method just because it looks cleaner and you don't need a release.
- I see a lot of alloc/init - what's the advantage to doing it this way?
My Question
- Which one is preferable? Or is it just a matter of taste?
Code
For context, the class Product would have the following:
+(Product *)productWithIdentifier:(NSString *)identifier_ {
return [[[[self class] alloc] initWithIdentifier:identifier] autorelease];
}
-(Product *)initWithIndentifier:(NSString *)identifier_ {
self = [super init]
if (self) {
identifier = identifier_;
}
return self;
}