In the following common sample,
////
@interface MyObject : NSObject
{
@public
NSString * myString_;
}
@property (assign) NSString * myString;
@end
@implementation MyObject
@synthesize myString = myString_;
@end
////
why declare myString_ in the interface at all?
I ask because we can still get and set myString in the implementation using self.myString, [self myString], self.myString = ... and [self setMyString:...] and in fact we must if instead it’s being retained.
With the modern Obj-C runtime, declaring the ivar is more of a formality than anything else. However, there are some memory management things to keep in mind.
First, the property declaration for an object type is usually
retain, or for strings it may becopy. In either case, the new object is retained.Given the following code:
The second assignment would leak; the first would not. This is because the property would retain something that already has a retain count of 1—it is now at 2. When you release the property in
dealloc, the count goes to 1, not 0, so it won’t be released. With the first option, however, the retain count stays at 1, sodeallocbrings it down to 0.In your example, leaving the property as
assignwill make the ivar declaration a formality.