Home > Articles > Home & Office Computing > Mac OS X

  • Print
  • + Share This
Like this article? We recommend

Like this article? We recommend


At first, in and of itself, this does not appear to be very useful. However, it is just the basic foundation of KVC. The next piece to look at is accessing child objects through its keypath, which is a way to access children of objects without having to retrieve the object in the middle. In the example above, if I wanted to retrieve value1 but I wanted it in all caps, one way of doing that would be the following:

NSString *value1 = [reference value1];
NSString *allCaps = [value1 capitalizedString];

Or by using the Wil Shipley{1} method:

NSString *allCaps = [[reference value1] capitalizationString];

By using KVO's keypath, I can retrieve the capitalized version in one call:

NSString *allCaps = [reference valueForKeyPath:@"value1.capitalizedString"];

This functionality can get even more complicated because there is no theoretical limit to how deep a keypath can be.

In addition to this direct referencing, there are operators that can be used in combination with KVO and either arrays or sets. For example, in the header above, let us imagine that array1 is an array of objects that contains an NSNumber stored in the instance variable "test". In a situation that is quite normal in Java, if I wanted to get the total of those NSNumbers I would have to do something like this:

double d = 0.0;
NSEnumerator *arrayEnum = [[reference valueForKey:@"array1"] objectEnumerator];
id item
while (item = [arrayEnum nextObject]) {
  d += [item test];

By using an operator on the array, all that code can be condensed into a single line:

double d = [[reference valueForKey:@"array1.@sum.test"] doubleValue];

There are several more operators that can be used on both NSArrays and NSSets. They are:


Detail on each of these operators can be found on Apple's website.

  • + Share This
  • 🔖 Save To Your Account