views:

130

answers:

3

How do I retain classes that I write?

+2  A: 

First, 'retain' has a very specific meaning in Cocoa applications. It is used in pair with 'release' to augment the internal reference counter of an instance of NSObject (i.e. any class that inherits from NSObject). As such, one does not retain a class, but rather one retains an instance of that class. This is done as such:

Person *person = [[[Person alloc] init] autorelease];
[person retain];

For more information see:

http://www.otierney.net/objective-c.html#retain

Kevin Sylvestre
A: 

retain and release are implemented in NSObject so you don't have to do anything for the release count mechanism to work with your custom classes. But maybe you could be more specific about your question ?

VdesmedT
A: 

I believe you are asking: "How can I keep objects I create within another class throughout its object's life?".

If so, the answer is to use properties with the retain keyword like so:

@property (nonatomic, retain) MyObject *myObject;

If you do this you should first synthesize it (this creates a getter and a setter)

@synthesize myObject;

and then you set the object (if you are in the object's class):

self.myObject = [[[MyObject alloc] init] autorelease];

then release it in dealloc:

- (void) dealloc
{
    [myObject release];
    [super dealloc];
}

All in all you will have something like this

MyViewController.h:

@interface MyViewController: UIViewController
{
    MyObject *myObject;
}

@property (nonatomic, retain) MyObject *myObject;

@end

MyViewController.m:

@implementation MyViewController

@synthesize myObject;

- (void) viewDidLoad
{
    [super viewDidLoad];
    self.myObject = [[[MyObject alloc] init] autorelease];
}

- (void) dealloc
{
    [myObject release];
    [super dealloc];
}

@end

There are lots of tutorials on properties out there. Here is one: http://macdevelopertips.com/objective-c/objective-c-properties-setters-and-dot-syntax.html

vakio