David Hall
David Hall

Reputation: 99

Easy iOS Line of Code Explanation

I am doing the 'Your Second App' tutorial and it has me add the line of code below that is a setter for the masterBirdSightingList property. I just have a basic questions on it:

Is this line the same as if I were to synthesize it? If not, what makes it different?

- (void)setMasterBirdSightingList:(NSMutableArray *)newList
{
     if (_masterBirdSightingList != newList) {
            _masterBirdSightingList = [newList mutableCopy];
     }
}

Upvotes: 0

Views: 104

Answers (1)

rmaddy
rmaddy

Reputation: 318824

If the property is defined as:

@property (nonatomic, copy) NSMutableArray *masterBirdSightingList;

then implementing this method is not the same as simply using @synthensize masterBirdSightingList;.

Defining a property with copy semantics for a mutable container type doesn't actually work as expected using the default synthesized setter.

Without the explicit method, you actually end up with the property referencing an immutable copy of the array.

By using the code you posted, instead of relying on the synthesized method, you get the proper and expected behavior of having a mutable copy of the original array.

Another way to look at this is that calling copy on an NSMutableArray returns an NSArray, not an NSMutableArray. This is why the default synthesized property setter doesn't work as expected (when dealing with a mutable container property). So you must implement the setter yourself and call mutableCopy on the parameter.

Upvotes: 3

Related Questions