Question about saving attribute with @property and @synthesize

I'm still pretty new to Objective-C coding (as evidenced by this question), and I think I don't quite understand how the use of the save attribute in the @property declaration works.

Here is an example class:

@interface Foo : NSObject { NSMutableArray *myArray; } @property (retain) NSMutableArray *myArray; 

My understanding was that adding a save attribute to the @property declaration (and using the necessary @synthesize decryption in the implementation file) will basically do the following settings and getter for me:

 - (void)setMyArray:(NSMutableArray *)newArray { myArray = [[NSMutableArray alloc] initWithArray:newArray]; [newArray release]; } - (NSMutableArray *)myArray { return myArray; } 

Is this accurate or am I mistaken how the save attribute works?

+1
objective-c
Dec 30 '09 at 14:34
source share
3 answers

Adding a save attribute will actually generate this code:

 - (void)setMyArray:(NSMutableArray *)newArray { [newArray retain]; [myArray release]; myArray = newArray; } - (NSMutableArray *)myArray { return myArray; } 

The reason the save method is called in newArray before release by the old value is because if newArray and myArray are the same object, the array will be released before it is saved again.

+5
Dec 30 '09 at 14:37
source share

This is really hard to do right. Take a look at Cocoa's Memory and Streaming Custom Property Methods article with love by Matt Gallagher.

Here's one implementation that works, greatly inspired by what a great article .

 - (void)setSomeString:(NSString *)aString { @synchronized(self) { if (someString != aString) // not necessary, but might improve // performance quite a bit { [aString retain]; [someString release]; someString = aString; } } } - (NSString *)someString { @synchronized(self) { id result = [someString retain]; } return [result autorelease]; } 
+1
Dec 30 '09 at 18:34
source share

retain will not copy the new value. He will retain the new meaning and release the old.

0
Dec 30 '09 at 14:37
source share



All Articles