Say I have an object called MyClass, which has a property defined as @property (nonatomic, retain) NSString *foo; and I synthesize that property.
Then in another class, say the application delegate I define a string (but it could be anything) NSString *myString = [[NSString alloc] initWithString:@"Hi"]; and call on an instance of MyClass: [myClass setFoo:myString];
What actually happens? Does the reference to the space that was allocated for myString get set? Or does it get what is in the allocated memory for myString and set it to the allocated memory for foo, since I called retain on foo?
And I have to release myString in the application delegate. And I have to release foo in MyClass, since it was retained, but do I have to release it again since another alloc’d variable was assigned to it?
It all depends how the property is declared. Because yours is
(retain), it will keep the same object pointer, and also automatically send-retainso it can ensure access to the memory whether or not the caller holds a reference. If you used(copy), it would send-copywhich would make a new object that’s a copy of the old one (provided the object conforms to `NSCopying).This all happens in the accessories implementation, which is commonly generated for you when you use
@synthesize. If you implement your own, be sure to use the correct behavior!