Re: Memory Management
Re: Memory Management
- Subject: Re: Memory Management
- From: "Mike Vannorsdel" <email@hidden>
- Date: Sun, 5 Aug 2001 14:41:29 -0600
This is common in custom classes. You can use init as your constructor
and dealloc as your destructor. ie:
- (id)init
{
self = [super init]; //initialize the object using the super
class's method
myArray = [[NSArray alloc] initWithObjects:@"Hello", @"World",
nil]; //init your array
return self; //return your object instance
}
- (void)dealloc
{
[myArray release]; //release your array, dealloc is called when
the object is going to be destroyed
[super dealloc]; //use the super class's method for instance
destruction
}
The init method may vary depending on your superclass. If NSView is the
superclass, you'd use initWithFrame: for the construction:
- (id)initWithFrame:(NSRect)frameRect
{
self = [super initWithFrame: frameRect];
myArray = [[NSArray alloc] initWithObjects:@"Hello", @"World", nil];
return self;
}
On Monday, August 6, 2001, at 07:45 AM, stuartbryson wrote:
I am currently learning about Mem management in Cocoa. I currently have
a class called world with a NSArray *myArray declared in the interface
file. The object has 2 main methods; Build and Render. I need to alloc
the array within the Build method (as this is where the array is
populated), and then use the array in Render and release it. I am not
sure if there is a better way to achieve this?
Perhaps I can write my own init method for my world class where it
declares the array and a "destructor" (C++ I know) method where I can
release the array. That way the array would not need to be handled in
Build or Render, just used. Does this make sense?
Also when the array is released, do the objects within the array
automatically get released... see the code below