Can someone explain the differences between free()
, release
, autorelease
and dealloc
?
The DEALLOC operation frees one previous allocation of heap storage. pointer-name is a pointer that must be the value previously set by a heap-storage allocation operation (either an ALLOC operation in RPG, or some other heap-storage allocation mechanism).
-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.
An autorelease pool is actually a collection of objects that will be released at some point in the future (either at the end of the thread's run loop or at the end of the scope of an autorelease pool). When a pool is drained, all the objects in the pool at that time are sent the release message.
Before releasing objects, the CLR automatically calls the Finalize method for objects that define a Sub Finalize procedure. The Finalize method can contain code that needs to execute just before an object is destroyed, such as code for closing files and saving state information.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With