开发者

Memory management semantics of Objective C "new"

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.


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


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜