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;
}
If you’re using ARC, there’s not that much of a difference between the two. If you’re not using ARC, the difference is extremely important.
The
alloc/initcombination gives you an owning reference. That means you mustreleaseit later on. TheclassnameWithFoovariant returns a non-owning reference. You may notreleaseit.This follows the usual Cocoa naming conventions. All methods return non-owning (autoreleased) instances, except for the methods that start with
alloc,copy,mutableCopyandnew. These return owning references that you mustrelease.Which one to use is mostly a matter of taste. However, if you need temporary objects that you can dispose quickly the
allocvariant results in slightly fewer method calls (theautorelease) and in a loop, it also reduces the maximum memory footprint. However, in most cases this reduced cost is neglectable.