开发者

What are the differences between free, dealloc, release, and autorelease?

Can someone explain the differences between free()开发者_运维技巧, release, autorelease and dealloc?


free() is a C function that you use to dispose of no longer needed memory you obtained through malloc() or other function that is documented to require free() to deallocate its memory e.g. strdup().

-dealloc is an Objective-C selector that is sent by the Objective-C runtime to an object when the object is no longer owned by any part of the application.

-release is the selector you send to an object to indicate that you are relinquishing ownership of that object. Once an object is not owned by anybody, it is sent the -dealloc message by the runtime.

-autorelease is a selector you send to an object to indicate you are relinquishing ownership of the object. However if nobody now owns the object the final -dealloc will be deferred until some unspecified later point. In fact, what you are really doing is transferring your ownership to an autorelease pool which will then release it when it is itself released (or drained).

You must never send -dealloc to an object except to super in the object's own -dealloc method.


Out of the 4 methods you've mentioned you'll typically only use release and autorelease in objective-c. free maybe used when you've used c and malloc otherwise you should use release and autorelease.

dealloc shouldn't be called by any of your code as it can interfere with the retain/release cycle that objective-c uses to keep track of resources. Using dealloc will almost certainly result in crashes at runtime if you ever use it.

The ultimate resource of the use of the release and autorelease is the Apple memory management documentation


  • free is the opposite of malloc and is used in C. You'll likely not use it very much programming in Objective C
  • If you own an object, you release it when you're done with it
  • You can also autorelease an object. This automatically releases it at the end of the current run loop iteration
  • When the reference count on an object drops to zero, the runtime calls dealloc. You should not call this method yourself

You "own" an object if you alloc, new, retain or copy it.

Apple provide some good documentation on this.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜