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
My Question
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/init
combination gives you an owning reference. That means you must release
it later on. The classnameWithFoo
variant returns a non-owning reference. You may not release
it.
This follows the usual Cocoa naming conventions. All methods return non-owning (autoreleased) instances, except for the methods that start with alloc
, copy
, mutableCopy
and new
. These return owning references that you must release
.
Which one to use is mostly a matter of taste. However, if you need temporary objects that you can dispose quickly the alloc
variant results in slightly fewer method calls (the autorelease
) and in a loop, it also reduces the maximum memory footprint. However, in most cases this reduced cost is neglectable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With