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
copyattribute in a property means the setter synthesized will look like this:and that dot syntax will always be translated to
regardless of the attribute of the property.
The “allocated for another space to preserve stuffs from sightingList” stuff is done via the
-copymethod. The way you pass the argument to the setter’snewValueparameter is irrelevant.Edit: As @David mentioned in the comment, the
-copymethod of a mutable type returns an immutable object. You have to override the setter to call-mutableCopyinstead. See What's the best way to use Obj-C 2.0 Properties with mutable objects, such as NSMutableArray?.