difference between drain, release,dealloc and retain in Objective-C/ - objective-c

Hi i want to know the difference between drain, release,dealloc and retain in Objective-C.

retain increase the reference count on an object
release decreases the reference on an object
drain is used in place of release on ONLY for NSAutoreleasePool objects due to some arcana related to the Objective C garbage collection
dealloc is called by the system once the retainCount of an object hits 0. It is where you clean up various things your object has (like a deconstructor or finalizer). You should NEVER call it directly, except for calling [super dealloc] at the end of your dealloc routines.
You really should just read through Apple's memory management documentation.

Related

Dealloc and ARC

I read that when using ARC in Objective-C programming in Xcode the dealloc method is called automatically by the compiler. Under what circumstances is it called?
In order to avoid having too many variable names, when I need to repeatedly use the same classes to do multiple operations (and resetting the variable each time) I often declare the variables, set them to nil, and then assign values to them as I go. This ends up looking like this:
MyClass mc;
mc = [[MyClass alloc] init];
[mc doThis:someOption]
mc = [[MyClass alloc] init];
[mc doThis:someOtherOption];
//etc...
The method name alloc is short for "allocate" because it is the method where memory is allocated to the variable. Does the compiler automatically release the memory for sc every time I assign it a new value? I plan on using this method in a project of mine, and I don't want a lot of memory being allocated with all the times I call alloc to assign a new value to mc.
The compiler never calls dealloc. The compiler inserts retain, release and autorelease (more efficient equivalents, really) as necessary to follow the memory management rules.
When the compiler inserts said calls is up to the compiler and the details will change across different compiler versions and different optimization levels.
I.e. you shouldn't need to worry about it in general.
However, autorelease pressure can still be an issue, as can retain cycles. Thus, you should definitely poke about your app with the Allocations Instrument to both measure the high-water mark and make sure your app isn't leaking memory over time.
I read that when using ARC in Objective-C programming in Xcode the dealloc method is called automatically
In Objective-C, you never call -dealloc directly whether or not you're using ARC.
Under what circumstances is it called?
-dealloc is called when an object's retain count drops to zero. That is, it's called when all the objects that had previously asserted "ownership" of the object (by calling +alloc or -retain or -copy or +new) have renounced that ownership (by calling -release or -autorelease).
Does the compiler automatically release the memory for sc every time I assign it a new value?
If you're using ARC (and you should be), the compiler will insert appropriate calls to -retain, -release, etc. so that memory is managed appropriately. That said, you still need to understand how memory management works, and you should be familiar with the material in Advanced Memory Management Programming Guide.
Under ARC, your variable mc will hold a strong reference to only one instance of MyClass at a time, so when you allocate the second one and assign it to the variable, the first one should be getting deallocated, assuming your doThis: method doesn't do something that will create another strong reference to that instance, or that you're not doing anything else in your code that you've omitted that will keep a strong reference.
That being said, it would be a good idea for you to run your app with Instruments to see how much memory your app uses during this. Your instances shouldn't be getting autoreleased, so you shouldn't have to worry about them remaining around until the autorelease pool is drained, but I don't know what you might being doing when you init an instance of the class, or what you might be doing in your doThis: method, so if you're concerned, it's always a good idea to profile it with Instruments for memory allocations and leaks.

What exactly use of dealloc method in Objective c? when it will call?

My Question is When the dealloc method will cal before the application termination, If it happens , When the application terminates all the memory of the objects and application will be removed from memory, then what is the use of writing dealloc method?
This is a general question about memory management. You use dealloc in Objective-C, free in C etc. to clean the memory allocated for the variables that are no longer in use. When the application terminates of course all of the memory allocated by the application will be released. However, if your application keeps allocating memory as it runs, and if the user runs the application for long enough, unless you release unused memory, the device's memory would get eventually used up. This is why you need to use dealloc.
The dealloc method describes how the object will be released. When an object is being deallocated unless you override the dealloc method only the object's pointer will be released. Therefore, in order to release properties and fields in your object you need to manually release them in your dealloc method.

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.

Retain count and dealloc in iPhone

I want to ask about the iPhone application and objective C question. In the implementation program, there are function called 'dealloc', does this function only be called one time by the application?
For example, if I alloc a object and retain it 2 times, the retains count is 2 and I never use 'release' in the program, unless in the dealloc. Will the object be removed from the memory, or the objective will be removed from the memory. Thank you.
In the implementation program, there are function called 'dealloc', does this function only be called one time by the application?
Yes. -dealloc destroys the object. Trying to send any message to it again, including -dealloc is an error.
if I alloc a object and retain it 2 times, the retains count is 2
Careful. The retain count is at least 3. Other things than your code might retain the object. It's better not to worry to much about retain counts and only think in terms of ownership.
Each alloc, new, copy or retain is an claim of ownership. The object's dealloc method will only be called when all claims of ownership have been relinquished. A claim of ownership is relinquished by sending -release. So if you never release an object except in its own dealloc, you'll never release it.
dealloc is called once by the system when the object is destroyed (when its reference count reaches 0). If you have member variables in your class that you alloc in your init function, you must release them in your dealloc function.
If you give someone a pointer to one of those member objects and they retain it, the member could survive the release in your dealloc, but by sending a retain message they are taking responsibility for sending a release message later, ensuring its eventual destruction.

What is the difference between releasing and autoreleasing?

I still have some unclear understand about release and autorelease. What are the difference between both of them? I have this code. For facebook connection. I crash it sometimes when I go to Facebook login, I doubting maybe it is because I don't release the object nicely.? Thanks for any helps
if (_session.isConnected) {
[_session logout];
} else {
FBLoginDialog* dialog = [[[FBLoginDialog alloc] initWithSession:_session] autorelease];
[dialog show];
}
The Memory Management Programming Guide for Cocoa will soon be your best friend. In brief, object instances in Cocoa are memory managed using reference counting (unless, of course you're using garbage collection on OS X). An object indicates that it wants to 'retain' an ownership interest in an other instance--keep it from being deallocated--by sending it a -retain message. An object indicates that it wants to release that interest by sending the other instance a -release message. If the number of objects that have 'retained' and ownership interest in an object drops to 0 (i.e. when the last of the owning instances sends a -release message), the instance with a 0 retain count is deallocated.
It's sometimes convenient to say "I want this instance to be released some time in the future". That's the purpose of -autorelease. Sending an -autorelease message adds the receiver to the current NSAutoreleasePool. When that pool is drained, it sends a -release message to all the instances in the pool. An NSAutoreleasePool is automatically created at the start of each iteration of each thread's run loop and drained at the end of that iteration. Thus, you can do something like this in a method:
- (id)myMethod {
return [[[MyObject alloc] init] autorelease];
}
The caller of this method will get back an instance that they can -retain if they wish to keep it. If they don't retain it, it will stick around at least until the enclosing autorelease pool is drained:
- (void)someOtherMethod {
...
id instance = [obj myMethod];
... // do more with instance, knowing that it won't be dealloc'd until after someOtherMethod returns
}
Releasing means you release that right away.
Autoreleasing means you want the variable to be released on the next autorelease pool.
You use autorelease when you want to keep retaining the variable but don't want to create a memory leak. You use release when you don't need the variable anymore.
Sample:
- (NSNumber *)return5 {
NSNumber * result = [[NSNumber alloc]initWitnInt: 5];
[result autorelease];
return result;
}
Why do we use autorelease there?
If we use [result release] instead, variable result will be destroyed AT that time. Which means that the returned value will be garbage.
If we do not release at all, variable result will be hold FOREVER incurring memory leak.
We can tell every caller to the function to release result but that would be a headache and prone to error.
So we use autorelease. We mark the variable to be released on the next autorelease pool. Basically we mark the variable to be released near the alloc. Hence the mantra alloc is paired with release in the same function holds all the time.
Actually, you'll do fine changing all release into autorelease. Your memory use won't be efficient, however, the effect is minimal. All variables, in all programming language is effectively autoreleased.
Anyway, use ARC.
background discussion:
objective-c is reference counted, so objects are deleted when the reference count reaches 0. release reduces the reference-count immediately, autorelease reduces it when the autorelease-pool is popped
when to use:
use autorelease when allocating the object if
you do not need it after the current function
it will be retiained by some other objet/function and will be released by a later by the retaining code
when the logic of the current function is tricky, so you would have to send release in a dozen different places before doing a return
use "manual" release
to revert a previous retain (in case you are implementing a library)
if you need precise control of freeing objects (e.g. they use lots of memory or the autorelease pool will not be popped for some time)
but really my freand:
read the Memory Management Programming Guide for Cocoa as suggested by Barry and run your code with instruments (zombies and leaks) often to catch any and almost all memory management errors.
Erik
According to the Memory Management Programming Guide for Cocoa:
The autorelease method, defined by
NSObject, marks the receiver for later
release. By autoreleasing an
object—that is, by sending it an
autorelease message—you declare that
you don't want to own the object
beyond the scope in which you sent
autorelease.
Also:
The autorelease method thus allows
every object to use other objects
without worrying about disposing of
them.