Question

It seems like a nearly new superset over Objective-C, with the combinations of dot notation mixed with directives, e.g.: studentsInClassA.@union.studentsInClassB.pets(...) and compliance syntax, e.g.: -replaceObjectIn<Key>AtIndex:withObject:. It seems like a large portion of KVC is akin to simple accessor methods, which can be synthesized anyway. However, I will say that KVObserving seems to make MVC apps easier. Opinions?

Était-ce utile?

La solution

Key-value coding allows you to look up arbitrarily nested attributes whose identity is only known at runtime. For example, KVC is not a good replacement for person.name — it's needlessly generic for such a specific task. But let's say we didn't know when we were writing our program whether we wanted to look up the name, age or favorite shoe brand. We run into this sort of thing quite often with NSTableView data sources. We could write a big, repetitive conditional to send the message we want, but KVC makes it easy:

return [personController.selectedPerson valueForKeyPath:desiredAttribute];

Then we can set desiredAttribute to @"name", @"age" or @"favoriteShoeBrand.name" and we'll get the correct value without branching even though we only know the attribute we want at runtime.

It's also useful because classes can handle KVC in special ways. For example, NSArray does something really nice. [arrayOfPeople valueForKeyPath:@"name"] is not equivalent to arrayOfPeople.name — instead, it passes on the keypath to each object and creates a new array with the results of doing that. So it serves much the same purpose as the map function in many other languages. There are also special KVC operators, such as @distinctUnionOfArrays (which takes a collection of arrays and merges them together, ignoring duplicates), that make operating on nested collections this way much more concise than it otherwise would be.

As for KVO, it is just a way of getting notified when something changes — so, for example, you can update your UI with a new age on a person's birthday without the UI needing to know about the birthday logic. If that sounds useful to you, you'll probably like it.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top