views:

86

answers:

3

Is "new" an equivalent of "alloc init" or "alloc init autorelease"?

I cannot seem to find it in any tutorial or article that deals with Cocoa memory management.

Thanks for advise.

+9  A: 

How about this one. Read them, understand them, they're simple.

jer
+1 Please, please, please go read the Memory Management Guide for Cocoa. Then read it again.
Barry Wark
Also, the docs on `+new` in this one: http://developer.apple.com/library/mac/#documentation/cocoa/reference/foundation/Classes/NSObject_Class/Reference/Reference.html
JeremyP
+3  A: 

new returns an object with a retain count of 1, just like [[alloc] init]. The object is not autoreleased.

Firoze Lafeer
+1  A: 

+[NSObject new] is functionally equivalent to +[NSObject alloc] followed by -[NSObject init] (i.e. [[alloc] init]).

To answer your question, from the NSObject class docs:

If you are using managed memory (not garbage collection), this method retains the object before returning it. The returned object is not autoreleased. The invoker of this method is responsible for releasing the returned object, using either release or autorelease.

Using new is rare in modern Cocoa code. Most Cocoa developers favor explicit, clear code over saving a couple of key strokes. Thus alloc/init is preferred.

Barry Wark
Here is what the Cocoa documentation on `NSObject +new` says: *Allocates a new instance of the receiving class, sends it an init message, and returns the initialized object... This method is a combination of alloc and init...* If that's scarily inexplicit, there can't be much that is explicit.
JeremyP
@JeremyP The docs have been updated since I last looked.
Barry Wark