DWB
DWB

Reputation: 1554

Setter method is odd, can someone explain

I'm taking a look at the developer library for iOS. A property called masterBirdSightingList was created with type NSMutableArray.Thats fine, in the implementation they added this peice of code

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

In order to

To implement a custom setter for the master list property ... (and) to override its default setter method to make sure that the new array remains mutable.

I'm not quite sure why this is fully necessary. Surely the array cannot suddenly change from a mutable array to something static. Is this method necessary?

Could you also help clarify whether the method setMasterBirdSightingList is called every time the masterBirdSightingList is set?

The tutorial I'm talking about is available here about halfway down the page.

Thank you

Upvotes: 2

Views: 73

Answers (1)

user529758
user529758

Reputation:

Could you also help clarify whether the method setMasterBirdSightingList is called every time the masterBirdSightingList is set?

Yes, it is - in Objective-C, property access is implemented using getter and setter methods. No exception. The dot notation is just syntactic sugar for - (T)foo and - (void)setFoo:(T)arg.

I'm not quite sure why this is fully necessary.

Because if you just declared a copy property, then upon setting the array, it would be sent the copy message, and that returns an immutable copy (in Cocoa [Touch], it's a common convention that copy returns an immutable copy, even if the original object was mutable.)

This is why explicitly sending mutableCopy to the argument is needed.

Upvotes: 3

Related Questions