KVC and to-many relationships


#1

I am not sure I fully understand this aspect of the chapter.

You write:

“If you want to use key-value coding to manipulate that array you will ask the playlist for its mutableArrayValueForKey:. You will get back a proxy object.”

Then you show this snippet:

id arrayProxy = [playlist mutableArrayValueForKey:@"songs"]; int soungCount = [arrayProxy count];

But why is that? Why couldn’t I just:

id array = [playlist valueForKey:@"songs"]; int songCount = [array count];


#2

This is a somewhat subtle area. You’re correct, however, the examples you cite are the same.

However, the to-many KVC accessors allow us to respond to mutations of a mutable array in a way that wouldn’t otherwise be possible. In this chapter, by implementing -insertObject:inEmpoyeesAtIndex: and -removeObjectFromEmployeesAtIndex:, we can respond to objects being added and removed from the array, as long as they are doing so in a KVC-compliant way (like NSArrayController does).

-mutableArrayValueForKey: is illustrating how we can obtain a proxy NSMutableArray object that allows us to act as if we were operating directly on the model’s NSMutableArray, and still provide KVO notifications via bindings and so forth.

Adam


#3

[quote=“AdamPreble”]This is a somewhat subtle area. You’re correct, however, the examples you cite are the same.

However, the to-many KVC accessors allow us to respond to mutations of a mutable array in a way that wouldn’t otherwise be possible. In this chapter, by implementing -insertObject:inEmpoyeesAtIndex: and -removeObjectFromEmployeesAtIndex:, we can respond to objects being added and removed from the array, as long as they are doing so in a KVC-compliant way (like NSArrayController does).

-mutableArrayValueForKey: is illustrating how we can obtain a proxy NSMutableArray object that allows us to act as if we were operating directly on the model’s NSMutableArray, and still provide KVO notifications via bindings and so forth.

Adam[/quote]

Thanks for the answer Adam.

So basically deep down in NSArrayControllers innards, it calls -mutableArrayValueForKey: and not just -valueForKey: to get the proxy object with this added functionality. And by being more KVC compliant with our document object, we can respond to these actions as adding and removing objects to/from the array.


#4

That was the one thing that wasn’t quite clear enough for me in this chapter: why proxy objects are valuable here. Thanks for clarifying.