Re: Yet another memory management question
Re: Yet another memory management question
- Subject: Re: Yet another memory management question
- From: WT <email@hidden>
- Date: Sun, 5 Jul 2009 05:11:10 +0200
On Jul 5, 2009, at 4:39 AM, DKJ wrote:
Is this the right way to do it?
Not quite...
- (void)viewDidLoad
{
id myObject = [[NSObject alloc] init];
}
Your myObject is a local variable, so it will go out of scope when
viewDidLoad returns. That means you won't be able to refer to the
object it points to in other methods (such as viewDidUnload and
dealloc).
The following is ok, though, assuming that you have appropriately
declared myObject in your class (for example, as an instance variable):
- (void)viewDidLoad
{
myObject = [[NSObject alloc] init];
}
Note the absence of 'id'.
- (void)viewDidUnload
{
[myObject release];
myObject = nil;
}
- (void)dealloc
{
[myObject release];
}
Both are fine, but I would suggest something like the following, just
because it avoids code duplication:
- (void)viewDidUnload
{
[self dispose];
}
- (void)dealloc
{
[self dispose];
// deallocation of stuff that was not unloaded
[otherStuff release];
}
- (void)dispose
{
[myObject release];
myObject = nil;
}
You can have -dispose be a private method of your class so it won't be
accessible outside of it. One big advantage of this separation is that
if/when you need to change your deallocations, you only have to do it
in one place.
I would recommend that you read the Cocoa Memory Management Guide for
all the details on memory management:
http://developer.apple.com/documentation/Cocoa/Conceptual/MemoryMgmt/MemoryMgmt.html
Wagner
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden