Reputation: 7758
The KVC Documentation says
The key-value coding method setNilValueForKey: method is called when you attempt to set an attribute to nil.
Sounds good so far
... uses setValue:forKey: to set the new value. This maintains encapsulation of the model and ensures that any additional actions that should occur as a result of setting the value will actually occur. This is considered better practice than calling an accessor method or setting an instance variable directly.
Why is it better practice to call the -setValue:forKey:
inside the -setNilValueForKey:
method when setting a 'default' value on a primitive or value type property? Is there a performance or technical advantage to using the KVC method -setValue:forKey:
opposed to the property accessor (I'm assuming that when it says accessor method it applies to accessor properties as well since they're just syntatic sugar over the method)? Usually when Apple recommends a 'best practice' there is a performance or reliability concern backing it. Does anybody know a documented reason why?
Upvotes: 4
Views: 1163
Reputation: 39905
From your quote:
This maintains encapsulation of the model and ensures that any additional actions that should occur as a result of setting the value will actually occur.
Calling setValue:forKey:
instead of an accessor or changing the ivar ensures that all proper side effects are maintained. When the quote mentions maintaining encapsulation, it means staying in KVC methods instead of custom accessors. Calling setValue:forKey:
also means that you get the runtime to decide how the property should be set for you. Finally, the "additional actions" is probably referring to key-value observing. It will make sure the right methods are called, and not any that shouldn't be called.
Upvotes: 3