views:

1950

answers:

3

Learning Objective-C and reading sample code, I notice that objects are usually created using this method:

SomeObject *myObject = [[SomeObject alloc] init];

instead of:

SomeObject *myObject = [SomeObject new];

Is there a reason for this, as I have read that they are equivalent?

+15  A: 

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 (like initWithString)
  • alloc-init is more explicit than new

General opinion seems to be that you should use whatever you're comfortable with.

Jeremy Stanley
That custom initializer thing is a compelling reason to favor [[alloc] init]] over new in my opinion. Thanks for the lightning-quick answer.
willc2
If your class uses -init as the designated initializer, +new will call it. What Jeremy is referring to is if you have a custom initializer that isn't -init. -initWithName:, for example.
bbum
There is nothing that stops you from implementing `+newWithString:` as well, if you already implemented `-initWithString`. Not that common though. Personally I always use `new` when the designated initializer is `init`, just soo short and sweet.
PeyloW
+3  A: 

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].

Brian Campbell
+6  A: 

+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.

Barry Wark