Use of alloc init instead of new
There are a bunch of reasons here: http://macresearch.org/difference-between-alloc-init-and-new
Some selected ones are:
new
doesn't support custom initializers (likeinitWithString
)alloc-init
is more explicit thannew
General opinion seems to be that you should use whatever you're comfortable with.
Frequently, you are going to need to pass arguments to init
and so you will be using a different method, such as [[SomeObject alloc] initWithString: @"Foo"]
. If you're used to writing this, you get in the habit of doing it this way and so [[SomeObject alloc] init]
may come more naturally that [SomeObject new]
.
Very old question, but I've written some example just for fun — maybe you'll find it useful ;)
#import "InitAllocNewTest.h"
@implementation InitAllocNewTest
+(id)alloc{
NSLog(@"Allocating...");
return [super alloc];
}
-(id)init{
NSLog(@"Initializing...");
return [super init];
}
@end
In main function both statements:
[[InitAllocNewTest alloc] init];
and
[InitAllocNewTest new];
result in the same output:
2013-03-06 16:45:44.125 XMLTest[18370:207] Allocating... 2013-03-06 16:45:44.128 XMLTest[18370:207] Initializing...
+new
is equivalent to +alloc/-init
in Apple's NSObject
implementation. It is highly unlikely that this will ever change, but depending on your paranoia level, Apple's documentation for +new
appears to allow for a change of implementation (and breaking the equivalency) in the future. For this reason, because "explicit is better than implicit" and for historical continuity, the Objective-C community generally avoids +new
. You can, however, usually spot the recent Java comers to Objective-C by their dogged use of +new
.