You can forego the collection accessors; they aren't required. But they make things a lot easier.
One reason to have them, including countOfEmployees
, is efficiency: The employees
method may return a copy of the array object (particularly since the Office's copy is mutable, so the Office would not want other objects mutating the array out from under it), but if you only need to know the count or to access one object at a specific index, you don't need a copy.
The other reason is when the sender wants to mutate the property.
valueForKey:
will call employees
, which will ordinarily return an immutable copy.
- Returning a mutable copy would not help, since mutating that array would be mutating the copy, not the original through the property.
- Returning the original array will not enable the sender to cause KVO notifications for its changes, so nothing observing the property will know about those changes. This means the values shown in your UI will go stale (not be updated).
mutableArrayValueForKey:
returns a fake array that sends mutation messages (or, if nothing else, employees
and setEmployees:
messages) back to the original object. Accessor messages do cause KVO notifications, so anything observing the property will follow along with these changes, so your UI keeps up to date.
Of course, you could just send the accessor messages yourself. mutableArrayValueForKey:
is mainly for if you want to make changes to a property that isn't known at compile time; NSArrayController is, presumably, one user of this method. You aren't likely to need to use mutableArrayValueForKey:
in a regular application, and sending accessor messages yourself is, in my opinion, easier to read.
All of this goes for the Office as well, when it mutates its own array. It could just talk to its array object directly, but that wouldn't cause KVO notifications, so nothing else would know the value of the property had changed. You could post the KVO notifications yourself around each change, but that's a hassle and easy to forget. Collection accessors and mutableArrayValueForKey:
are two solutions to these problems: Each access is a single line of code that will cause KVO notifications.