Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would you use a class method constructor versus alloc/init?

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;
}
like image 400
John Gallagher Avatar asked Feb 19 '12 14:02

John Gallagher


1 Answers

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.

like image 73
DarkDust Avatar answered Oct 13 '22 13:10

DarkDust