views:

51

answers:

1

Hi,

As many objc developers, I ended-up reading and reading again the Apple Memory Management Programming Guide, because that's the best way to understand retain/release/autorelease mechanisms.

In this page, there is really an example I do not understand:

http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmAccessorMethods.html#//apple_ref/doc/uid/TP40003539-SW1

Blockquote

Technique 1

In technique 1, values returned by the getter are autoreleased within the calling scope:

- (NSString*) title {

return [[title retain] autorelease];

}

- (void) setTitle: (NSString*) newTitle {

if (title != newTitle) {

    [title release];

    title = [newTitle retain]; // Or copy, depending on your needs.

}

}

Because the object returned from the get accessor is autoreleased in the current scope, it remains valid if the property value is changed. This makes the accessor more robust, but at the cost of additional overhead. If you expect your getter method to be called frequently, the added cost of retaining and autoreleasing the object may not be worth the performance cost.

Technique 2

Like technique 1, technique 2 also uses an autorelease technique, but this time does so in the setter method:

- (NSString*) title {

return title;

}

- (void) setTitle: (NSString*) newTitle {

[title autorelease];

title = [newTitle retain]; // Or copy, depending on your needs.

}

The performance of technique 2 is significantly better than technique 1 in situations where the getter is called much more often than the setter.

Blockquote

Ok, after several minutes of intense thinking I ended up understanding what Apple says and the reason for having [[title retain] autorelease]. But how can I specify this for a setter if I want to synthetise it ? I only know retain or copy as accessor method for the setter. For example:

@property (retain) NSString* title

will make a retain on title each time I set a new value to title. But how to specify that the getter will do return [[title retain] autorelease] as in example one ? Is-it synthesized implicitly this way by XCode ?

Regards, Apple92

+2  A: 

If you're using @synthesize, you don't need to care about the getter and setter implementations, so long as you've specified the property options (retain, copy, etc.) correctly. The compiler will do the right thing for you.

Unless you see actual perf problems regarding the getters and setters (which would be doubtful), I wouldn't worry about how it's implemented internally.


If you really want to use a specific getter or setter, just implement it on your class. Even if you have an @synthesize statement, your implementation will be used. Alternatively, you can implement both the getter and setter, and leave out the @synthesize statement entirely.


OR you can specify the getter or setter accessor method name in your property declaration.

Robot K