What is dealloc in objective C - objective-c

I want to ask an general question about the objective C. When I write the program of the iPhone application, I always see a function called 'dealloc' in the .m. when will this method be called? do I need to put all the [release] in here good for the application? thank you very much.
// ------------------ updated content -------------------------
NSArray *arr;
NSString *str;
NSMutableArray *mutableArr;
// in the dealloc
// it should have to following
[arr release];
[str release];
[mutableArr release];
the function will be call 3 times?

The dealloc method is called on an object when it's retain count has reached zero. Retain counts are increased by one for each retain call, and reduced once for each release call. The autorelease schedules a future release call when the current NSAutoreleasePool is drained, typically at the end of an event cycle, but you can set up your own NSAutoreleasePools on memory intensive operations. (See the NSAutoreleasePool docs for details.)
What should you put into dealloc? You should put a release for each member object the object of that class retains.
A couple things make this easier. The nil object will quietly ignore any messages sent to it, so [foo release] when foo = nil is not a bug. However, releasing an object twice can cause serious issues. My (hardly unique) solution to this is to explicitly set whatever I just released to nil, whenever I release it. In fact, I put the nil assignment on the same line as the release so I can grep for "release" and find places I missed. Example:
#interface MyClass {
Foo *foo;
Bar *bar;
NSInteger baz;
}
-(void)dealloc;
#end
#implementation MyClass
-(void)dealloc {
[foo release]; foo = nil;
[bar release]; bar = nil;
[super dealloc];
}
#end
I'll assign nil to a variable even when that variable is about to go out of scope or the object is about to go away. Why? If another object of the same class is allocated in the same memory space after I've released this one, it guarantees there will be no dangling pointers the new object might accidentally use and make debugging a nightmare. (See also NSZombieEnabled for debugging help.)

when will this method be called?
It's called when the reference count for that object becomes 0 because all its pointers have been released. The memory taken up by it is deallocated (freed); the object itself is destroyed.
do I need to put all the [release] in here good for the application?
Yes, release all the properties of the object that are still retained.
EDIT: in response to your updated question, dealloc in your custom object is only called once. It will then send these three messages:
[arr release];
[str release];
[mutableArr release];
To each of the three objects. They are entirely different objects, but if you only have one instance of each, then their reference counts all go down to 0 and their dealloc methods are called automatically.

As you surmised, it's called when an object is destroyed. The object should release everything it owns.

In Other words, Dealloc frees/destroys/releases the memory you allocated to your objects.
Allocated objects to memory should be destroyed once not used to avoid memory leaks that might cause your application to crash.
ZaldzBugz

Related

How to release memory of a retained object

This is one of my method.
- (void)getSearchResultsByKeyword:(NSString *)keyword
searchOptions:(NSArray *)searchOptions
searchGroupsInResult:(NSArray *)searchGroupsInResult
{
_searchKeyword = [keyword retain];
_searchOptions = [searchOptions retain];
_searchGroupsInResult = [searchGroupsInResult retain];
[_searchResultsGroups removeAllObjects];
[_searchResultsGroupsIndexToNameMap removeAllObjects];
_pageNo = 1;
[[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:SearchResultsRetrievingStartLodingNotification
object:self];
[_dataProvider startGettingSearchResultsByKeyword:self.searchKeyword
searchOptions:_searchOptions
searchGroupsInResult:_searchGroupsInResult
pageNo:_pageNo
delegate:self];
}
In my method I have called retain on the objects which are parameters. So I have owned the object and has increased the retain count. So my problem is, how do I decrease the retain count after the
[_dataProvider startGettingSearchResultsByKeyword:self.searchKeyword
searchOptions:_searchOptions
searchGroupsInResult:_searchGroupsInResult
pageNo:_pageNo
delegate:self];
call. ( [keyword release] or [_searchKeyword release] ) ??
In my header file I have declared the _searchOptions as a private instance and _searchKeyword as a readonly property. In my implementation file, I have released both instances in dealloc.
I ran Analyze tool and it did not show this thing as an issue. But I have a doubt on it.
So, please show me a necessary way to work on this thing.
I'm working on XCode4 and iOS 4.3.
Thanks.
jaydee3's answer is correct. I would add that you really should use #properties with synthesized accessors. Then, instead of setting your instance variables directly, use the accessor methods. That way you can encapsulate all of the memory management of your instance variables in the accessor methods. This has the advantage of being more readable, much less error prone, and makes your code easier to modify in the future.
So, in your .h (or in a class extension in your .m if the properties should be "private"):
#property (nonatomic, copy) NSString *searchKeyword;
In your .m:
- (void)dealloc
{
self.searchKeyword = nil;
[super dealloc];
}
#synthesize searchKeyword = _searchKeyword;
Finally, in your -getSearchResultsByKeyword:searchOptions:searchGroupsInResult: method:
self.searchKeyword = keyword;
instead of
_searchKeyword = [keyword retain];
Now you don't have to worry about releasing or retaining searchKeyword. The setter method generated by the #synthesize directive will take care of it for you. I suggest reading Apple's documentation on Declared Properties.
Since you are assigning to an ivar, you have to retain it. This is correct.
Releasing it within dealloc is also correct. But thats not enough. Two things:
1) It's better to copy strings, rather than retain them. So use _searchKeyword = [keyword copy];. (This is also retained. So the retainCount is 1 after that.)
2) Also there is a problem, when you call your method the second time. That is the point, where you do have a leak. You are assigning a new value to your ivar `_searchKeyword', dismissing the pointer to the old keyword, which is still retained. So before assigning the new one, release the old one also.
Example:
[_searchKeyword release];
_searchKeyword = [keyword copy];
If you copy it, this is good, but if you only retain, it would be even better to do it like that (in case both reference the same object):
[keyword retain];
[_searchKeyword release];
_searchKeyword = keyword;
When there are two objects that are pointers to the same thing, it doesn't matter which one you call release on. The thing pointed at is where the reference count gets decremented.
Given you've released it in one place, and the analyzer isn't complaining, you don't have a problem.

Strange memory only when using copy

I have a class named SomeClass. in its init I have a lot of lines like:
SomeProperty_ = [[SomeObject alloc] initWithSomething];
While the properties are declared as
#property(retain) SomeObject *SomeProperty;
and defined as
#synthesize SomeProperty = SomeProperty_;
When I allocate objects of SomeClass and later release them, everything works fine and there are no memory leaks. However, when I copy an object of SomeClass and later release it, all the lines like
SomeProperty_ = [[SomeObject alloc] initWithSomething];
are marked as a memory leak in Instruments. this is also correct as I get memory warning and later crash if I use this a lot.
However if I make a method named dealloc like:
-(void) dealloc
{
self.SomeProperty = nil;
[super dealloc];
}
Everything is fine with copies as well and no memory warning or leaks.
I think this is because of my copy implementation:
-(id)copy
{
SomeClass *copy = [[SomeClass alloc] init];
copy.SomeProperty.somePOD = self.SomeProperty.somePOD;
return copy;
}
Where is the problem? what can I do to resolve it without the custom dealloc?
The first things I can think of is:
How your somePOD is set as far as #property(???)
And when you say :
"However, when I copy an object of SomeClass and later release it, all the lines like
SomeProperty_ = [[SomeObject alloc] initWithSomething];
are marked as a memory leak in Instruments. this is also correct as I get memory warning and later crash if I use this a lot."
You are referring to call made in your init method?
Because if your not, you are bypassing a setter and the object that was in that variable before this assignment will leak.
You must either use a custom dealloc method or start using Automatic Reference Counting (ARC).
When you call [[SomeObject alloc] init...], you get ownership of the new object, so you must release the object when you are done with it. Setting self.SomeProperty to nil does the release because you declare the property with the retain attribute.
You do this in your dealloc method if you want to own the SomeObject object until your SomeClass object dies. If you use ARC, it will generate the dealloc method for you.

Object's ownership, after "return". Clarification needed

Assuming, the following declaration for class A
#property(nonatomic, assign) DoublyLinkedList *doublyLinkedList;
, that as part of init, initialized the object
- (id)init {
self = [super init];
if (self) {
doublyLinkedList = [[DoublyLinkedList alloc] init];
}
return self;
}
and that a method
- (DoublyLinkedList*) doSomethingAndReturn {
that ultimately
return doublyLinkedList;
Does class A owns the doublyLinkedList after the return?
EDIT: init added with alloc
You are not calling retain on it, but in init you are calling alloc on it, so it does have a retain count of 1 -- you own it and you should release it in dealloc.
You could simply alloc it and release it in dealloc. The caller of the property can choose whether to retain. Another option would be to create the object in init, autorelease it and then assign it to the property with (retain) instead of (assign). That way, if other places in the code alloc and assign to that property, the object you alloc'd will get released. Then in dealloc, what it's currently assigned to will get released.
Yet another option if you don't want others to set it would be to have a (readonly) property and a _doubleLinkedList iVar and then #synthesize doublyLinkedList = _doubleLinkedList. Then you can allocate it once in init and know that no one else will assign it, and then release it in dealloc.
A good analogy is that when you retain, you're putting a leash on it. Multiple items can put a leash on that object. It is freed only when everyone has taken the leash off.
A good guide to read:
Apple's Memory Management Programming Guide
Specifically from that doc, these rules help:
You own any object you create You create an object using a method
whose name begins with “alloc”, “new”, “copy”, or “mutableCopy” (for
example, alloc, newObject, or mutableCopy).
You can take ownership of an object using retain A received object
is normally guaranteed to remain valid within the method it was
received in, and that method may also safely return the object to its
invoker. You use retain in two situations: (1) In the implementation
of an accessor method or an init method, to take ownership of an
object you want to store as a property value; and (2) To prevent an
object from being invalidated as a side-effect of some other operation
(as explained in “Avoid Causing Deallocation of Objects You’re
Using”).
When you no longer need it, you must relinquish ownership of an
object you own You relinquish ownership of an object by sending it a
release message or an autorelease message. In Cocoa terminology,
relinquishing ownership of an object is therefore typically referred
to as “releasing” an object.
You must not relinquish ownership of an object you do not own This
is just corollary of the previous policy rules, stated explicitly.
Objects aren't really "owned" in that way. Objective-C will free up the memory for an object when its retain count gets to 0. If class A depends on doubleLinkedList being "kept alive" as long as an instance of class A is alive, then object A retains doublyLinkedList to increase that retain count by 1. When object A returns a reference to doublyLinkedList as you have above, then the caller who receives that result may elect to retain the object as well, which would increase the retain count by one again.
So try not to think of it as owning an object. Instead, think of it as expressing an interest in the existence of an object. As long as someone continues to be interested in that object, as expressed by its retain count, then the object will not be deallocated.
As you've defined it, class A has not ever retained doublyLinkedList. So no, it has no stake in it. In fact because doublyLinkedList is not retained by class A, it could be deallocated at any time during execution and cause an EXEC_BAD_ACCESS crash.
There are two obvious ways to deal with this.
Class A should retain doublyLinkedList while it's using it, and autorelease it before it returns it.
Another 'parent' object can retaining both doublyLinkedList and the instance of class A, and it's up to that 'parent' object to make sure doublyLinkedList doesn't get deallocated while the class A object is using it.
Edit:
If you alloc-init the object when you initialize Class A, as you've added above, then you should only release the object when Class A is deallocated. This makes for a simple object life-cycle. An instance of Class A is created, it creates a DLL object. That object persists until the Class A instance is destroyed. If other objects want to use the DLL, they simply request it from the class A instance, and retain it.
The goal with retain release is to code in such a way that you can be sure you have an EVEN number of retain calls, and release calls on an object. For every:
- (id)init {
self = [super init];
if (self) {
doublyLinkedList = [[DoublyLinkedList alloc] init];
}
return self;
}
You need a:
-(void)dealloc {
[super dealloc];
[doublyLinkedList release]
}
If your class a object is going to be creating and processing more than one DLL object, then don't create it in -(id)init and use retain for the property declaration.
then:
ClassA *newClassAObject = [[ClassA alloc] init]; // create class a object
newClassAObject.doublyLinkedList = [[[DoublyLinkedList alloc] init] autorelease]; // make a DLL object, only retained by class a object.
DoublyLinkedList *dll = [newClassAObject doSomethingAndReturn]; // process the list somehow
[dll retain] // we own this now
newClassAObject.doublyLinkedList = nil; // class A object gives up interest in dll.
newClassAObject.doublyLinkedList = [[[DoublyLinkedList alloc] init] autorelease]; // now process another one.
... and on and on ...

Use autorelease when setting a retain property using dot syntax?

I see in some sample code that autorelease is used. I am not familiar with the instances when this is required. For example, if I create an annotation object
Header file
#interface someViewController: UIViewController
{
Annotation *annotation;
}
#property (nonatomic, retain) Annotation *annotation;
#end
Implementation file
#implementation someViewController
#synthesize annotation
#end
Question: Is it the correct approach if I initialize my annotation object in the implementation file like this?
self.annotation = [[Annotation alloc] initWithCoordinate:location];
Do I need to set autorelease for this? Or can I just do it the normal way and add the release in the dealloc method?
this is correct:
self.annotation = [[[Annotation alloc] initWithCoordinate:location] autorelease];
because annotation property is declared as a retain property, so assigning to it will increment its retain count.
you will also need, all the same, to release self.annotation in -dealloc.
in short:
init will set retain count to 1;
assigning to self.annotation, will set it to 2;
autorelease will set it back to 1 when the main loop is executed again;
release in dealloc will set the retain count to 0, so that the object will be deallocated);
the best way to think of autorelease is the following, in my opinion: autorelease will "schedule" an "automatic" release for your object at some (near) point in future (typically when the control flow goes back to the main loop, but details are hidden in the hands of Apple).
autorelease is mostly useful in conjunction with init, specifically in the following cases:
when you init a local variable, so that you don't have to release it explicitly before it goes out of scope (the main loop will do that for you);
when you return a pointer to an object you have just created without keeping ownership of it (typical case of the create/make* kind of selectors, the receiver is required to retain it to get ownership);
with properties that retain, when you assign to them an object that they should own uniquely;
with data structures that increment the retain count (NSMutableArray, NSMutableDictionary, etc): you should generally autorelease a newly inited object when you add it to such data structure.
apart from case 2, it is evident that the use of autorelease is meant to improve readability of the code and reduce the potential for errors (meaning that in all of the other cases, you could simply release explicitly your object after the assignment or at the end of the scope).
when using properties, you have always to check whether they are of the retain or assign/copy case; in the first case, assigning a newly inited object to a property generally requires autorelease.
Anyway, I would suggest at least skimming one of the many tutorial on memory management for iOS.
Autorelease is telling the object to release itself before leaving the scope.
Sometimes when you code, you'll encounter something like this
- (void)doSomething
{
if(true)
{
NSString *foo = [[NSString alloc] initWithString:#"foo"];
//Some execution here
[foo release];
}
}
- (void)doSomething
{
if(true)
{
//By doing this is telling to to release foo object before getting out of the scope
//which is similar with above practice
NSString *foo = [[[NSString alloc] initWithString:#"foo"] autorelease];
//Or you can do it this way
NSString *foo = [[NSString alloc] initWithString:#"foo"];
[foo autorelease];
//Some execution carry on, it'll release foo before entering next scope
}
//This is out of the scope
}
Of course, releasing an object doesn't mean deallocating the object.
Sometimes you retain the object so you can still use it outside of its scope.
Judging from your question, if your the object is located within your header file/interface.
You should release it in dealloc method. CMIIW.

Why does this create a memory leak (iPhone)?

//creates memory leak
self.editMyObject = [[MyObject alloc] init];
//does not create memory leak
MyObject *temp = [[MyObject alloc] init];
self.editMyObject = temp;
[temp release];
The first line of code creates a memory leak, even if you do [self.editMyObject release] in the class's dealloc method. self.editMyObject is of type MyObject. The second line incurs no memory leak. Is the first line just incorrect or is there a way to free the memory?
The correct behavior depends on the declaration of the editMyObject #property. Assuming it is delcared as
#property (retain) id editMyObject; //id may be replaced by a more specific type
or
#property (copy) id editMyObject;
then assignment via self.editMyObject = retains or copies the assigned object. Since [[MyObject alloc] init] returns a retained object, that you as the caller own, you have an extra retain of the MyObject instance and it will therefore leak unless it there is a matching release (as in the second block). I would suggest you read the Memory Management Programming Guide[2].
Your second code block is correct, assuming the property is declared as described above.
p.s. You should not use [self.editMyObject release] in a -dealloc method. You should call [editMyObject release] (assuming the ivar backing the #property is called editMyObject). Calling the accessor (via self.editMyObject is safe for #synthesized accessors, but if an overriden accessor relies on object state (which may not be valid at the calling location in -dealloc or causes other side-effects, you have a bug by calling the accessor.
[2] Object ownership rules in Cocoa are very simple: if you call a method that has alloc, or copy in its signature (or use +[NSObject new] which is basically equivalent to [[NSObject alloc] init]), then you "own" the object that is returned and you must balance your acquisition of ownership with a release. In all other cases, you do not own the object returned from a method. If you want to keep it, you must take ownership with a retain, and later release ownership with a release.
Your property is declared "retain" meaning that it the passed in object is automatically retained.
Because your object already had a reference count of one from alloc/init there's then two references and I'm assuming only one release (in your destructor).
Basically the call to self.editMyObject is really doing this;
-(void) setEditMyObject:(MyObject*)obj
{
if (editMyObject)
{
[editMyObject release];
editMyObject = nil;
}
editMyObject = [obj retain];
}
By convention in Cocoa and Cocoa-touch, any object created using [[SomeClass alloc] initX] or [SomeClass newX] is created with a retain count of one. You are responsible for calling [someClassInstance release] when you're done with your new instance, typically in your dealloc method.
Where this gets tricky is when you assign your new object to a property instead of an instance variable. Most properties are defined as retain or copy, which means they either increment the object's retain count when set, or make a copy of the object, leaving the original untouched.
In your example, you probably have this in your .h file:
#property (retain) MyObject *editMyObject;
So in your first example:
// (2) property setter increments retain count to 2
self.editMyObject =
// (1) new object created with retain count of 1
[[MyObject alloc] init];
// oops! retain count is now 2
When you create your new instance of MyObject using alloc/init, it has a retain count of one. When you assign the new instance to self.editMyObject, you're actually calling the -setEditMyObject: method that the compiler creates for you when you #synthesize editMyObject. When the compiler sees self.editMyObject = x, it replaces it with [self setEditMyObject: x].
In your second example:
MyObject *temp = [[MyObject alloc] init];
// (1) new object created with retain count of 1
self.editMyObject = temp;
// (2) equivalent to [self setEditMyObject: temp];
// increments retain count to 2
[temp release];
// (3) decrements retain count to 1
you hold on to your new object long enough to release it, so the retain count is balanced (assuming you release it in your dealloc method).
See also Cocoa strategy for pointer/memory management
The first version creates an object without a matching release. When you alloc the object, it means you are an owner of that object. Your setter presumably retains the object (as it should), meaning you now own the object twice. You need the release to balance the object creation.
You should read the Cocoa memory management guide if you plan to use Cocoa at all. It's not hard once you learn it, but it is something you have to learn or you'll have a lot of problems like this.
Everyone else has already covered why it causes a memory leak, so I'll just chime in with how to avoid the 'temp' variable and still prevent a memory leak:
self.editMyObject = [[[MyObject alloc] init] autorelease];
This will leave your (retain) property as the sole owner of the new object. Exactly the same result as your second example, but without the temporary object.
It was agreed and explained that the code below does not have a leak
(assuming #property retain and #synthesize for editMyObject) :
//does not create memory leak
MyObject *temp = [[MyObject alloc] init];
self.editMyObject = tempt;
[temp release];
Question : is anything wrong with the following code that does not use a temp pointer ?
//does not create memory leak ?
self.editMyObject = [[MyObject alloc] init];
[editMyObject release];
To me this looks ok.