Thursday, June 18, 2009

Accessor Methods: "Retain, then Release" methodology

From "Cocoa(R) Programming for Mac(R) OS X (3rd Edition)" by Aaron Hillegass

If you have a nonpointer type, the accessor methods are quite simple. For example, if your class has an instance variable called foo of type int, you would create the following accessor methods:

- (int)foo
{
return foo;
}

-(void)setFoo:(int)x
{
foo = x;
}

MATTERS BECOME MORE COMPLICATED IF FOO IS A POINTER TO AN OBJECT. In the "setter" method, you need to make sure that the new value is retained and the old value released, as shown below:

-(void)setFoo:(NSCalendarDate *)x
{
[x retain];
[foo release];
foo = x;
}

No comments:

Post a Comment