I'm following an official tutorial Your second iOS App:Storyboard and it told me to declare a property masterBirdSightingList like this(just a specific example and not necessary to know the context) :
@property (nonatomic, copy) NSMutableArray *masterBirdSightingList;
Note that there's an attribute copy . and then synthesize this property :
@synthesize masterBirdSightingList = _masterBirdSightingList;
And next there's one init method which made me confused :
- (void)initializeDefaultDataList {
NSMutableArray *sightingList = [[NSMutableArray alloc] init];
self.masterBirdSightingList = sightingList;
[self addBirdSightingWithName:@"Pigeon" location:@"Everywhere"];
}
Definitely sightingList is allocated for spaces and then it's assigned to the masterBirdSightingList property. The property has a copy attribute, though. it means the instance variable _masterBirdSightingList would be allocated for another space to preserve stuffs from sightingList . Why? Why not directly allocate space for the property like this :
self.masterBirdSightingList = [[NSMutableArray alloc] init];
In Objective-C, the copy
attribute in a property means the setter synthesized will look like this:
-(void)setMasterBirdSightingList:(NSMutableArray*)newValue
{
if (_masterBirdSightingList == newValue) return;
// NSMutableArray* oldValue = _masterBirdSightingList;
_masterBirdSightingList = [newValue copy];
// [oldValue release]; // <-- not applicable in ARC.
}
and that dot syntax will always be translated to
[self setMasterBirdSightingList:sightingList];
regardless of the attribute of the property.
The "allocated for another space to preserve stuffs from sightingList" stuff is done via the -copy
method. The way you pass the argument to the setter's newValue
parameter is irrelevant.
Edit : As @David mentioned in the comment, the -copy
method of a mutable type returns an immutable object. You have to override the setter to call -mutableCopy
instead. See What's the best way to use Obj-C 2.0 Properties with mutable objects, such as NSMutableArray? .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.