KVC1: See KVC In Action
The code for this article is called KVO1, available on the download page. This project consists of a single class, AppController that looks like this:

You can see the three ivars I am interested in accessing: bob, jim, and fred. The idea here is that I will access these without writing any accessors. So the application lets the user specify the ivar by name to display:

The user types in the ivar name in the top field, presses the Show button, and the bottom field shows the value. That's all it does. Build the project and run it.
Here is the whole of the code for AppController:

-awakeFromNIB: does the initialization. It does access the ivars directly, and that is OK because the I don't care how the values are initialized. This program is written to show how KVC is used to read values.
All of the interesting stuff is in -show:. name is read from the top field and then used as an argument to valueForKey: to retrieve the string from the appropriate ivar and write it to the bottom field.
The run log shows the string Hello being output by the NSLog line:

If you type in something that does not correspond to an ivar name, such as george, you get this:

The bottom field was never updated. And that is because this happened:

What this is saying is that it failed to find an ivar called george, and so was unable to continue. It looked for accessors first, then gave up and tried to access the ivar directly and that failed too. I will improve on this behavior in the next installment.

You can see the three ivars I am interested in accessing: bob, jim, and fred. The idea here is that I will access these without writing any accessors. So the application lets the user specify the ivar by name to display:

The user types in the ivar name in the top field, presses the Show button, and the bottom field shows the value. That's all it does. Build the project and run it.
Here is the whole of the code for AppController:

-awakeFromNIB: does the initialization. It does access the ivars directly, and that is OK because the I don't care how the values are initialized. This program is written to show how KVC is used to read values.
All of the interesting stuff is in -show:. name is read from the top field and then used as an argument to valueForKey: to retrieve the string from the appropriate ivar and write it to the bottom field.
The run log shows the string Hello being output by the NSLog line:
If you type in something that does not correspond to an ivar name, such as george, you get this:

The bottom field was never updated. And that is because this happened:
What this is saying is that it failed to find an ivar called george, and so was unable to continue. It looked for accessors first, then gave up and tried to access the ivar directly and that failed too. I will improve on this behavior in the next installment.
KVC2: Adding valueForUndefinedKey
Download and open up KVO2. Confusingly the folder it is in is called KVO2, but the project is called KVO1. C'est la vie. Changing application and project names in XCode is difficult and error prone, so I did not bother. The window does have a new name, however.
KVO1 had the problem that if you type in something that does not correspond to an ivar name, such as george, you get this:

The bottom field was never updated. And that is because this happened:

What this is saying is that it failed to find an ivar called george, and so was unable to continue. It looked for accessors first, then gave up and tried to access the ivar directly and that failed too.
There is one change in KVO2. It adds a new method, one that is part of the Key Value Coding informal protocol:

If the key used (entered in the top field) cannot be found, then instead of giving up, this method is called. It simply prefixes the key with "Unknown: " and returns it as the ivar value. lets see it in action:

And now there is nothing in the run log.
KVO1 had the problem that if you type in something that does not correspond to an ivar name, such as george, you get this:

The bottom field was never updated. And that is because this happened:
What this is saying is that it failed to find an ivar called george, and so was unable to continue. It looked for accessors first, then gave up and tried to access the ivar directly and that failed too.
There is one change in KVO2. It adds a new method, one that is part of the Key Value Coding informal protocol:

If the key used (entered in the top field) cannot be found, then instead of giving up, this method is called. It simply prefixes the key with "Unknown: " and returns it as the ivar value. lets see it in action:

And now there is nothing in the run log.
KVC3: Adding A Custom Class
Download and open up KVO3. KVO3 (again the project is called KVO1) starts a new application, this time with an AppController object and a Car object. Here is what its window looks like:

You enter the name of the ivar you want to see and its values are shown below when you press Show. The Car class looks like this:

and its implementation is:

It simply sets up default values for each object instance when initialized and handles thee undefined key as before. There are no accessors here. If I try an ivar that does not exist, I get the Unknown message again:

In AppController, I have two Cars defined, suv and convertible.:

and the code that accesses these is:

The message valueForKey is simply sent to each of the Car objects to get the values for the fields. And I didn't write any accessor code for the Car class.

You enter the name of the ivar you want to see and its values are shown below when you press Show. The Car class looks like this:

and its implementation is:

It simply sets up default values for each object instance when initialized and handles thee undefined key as before. There are no accessors here. If I try an ivar that does not exist, I get the Unknown message again:

In AppController, I have two Cars defined, suv and convertible.:

and the code that accesses these is:

The message valueForKey is simply sent to each of the Car objects to get the values for the fields. And I didn't write any accessor code for the Car class.
KVC4: Using A Dictionary Instead Of ivars
Download and open up KVO4. Here is KVO4 running:

This Key Value Coding example replaces the individual ivars of KVO3 with a dictionary and adds a third car. It also replaces the Car class with a Vehicle class. AppController now contains an ivar called cars that is an NSMutableDictionary containing Vehicles:

The Vehicle class has no accessors.
AppController reads the values out by using valueForKey twice: once to access the dictionary to find the Vehicle, and then again to access the ivar inside the Vehicle object:

And since the Vehicle class handles the unknown key case by returning an "Unknown: " string:

we get the same kind of result as we did for the Car class.

This Key Value Coding example replaces the individual ivars of KVO3 with a dictionary and adds a third car. It also replaces the Car class with a Vehicle class. AppController now contains an ivar called cars that is an NSMutableDictionary containing Vehicles:

The Vehicle class has no accessors.
AppController reads the values out by using valueForKey twice: once to access the dictionary to find the Vehicle, and then again to access the ivar inside the Vehicle object:

And since the Vehicle class handles the unknown key case by returning an "Unknown: " string:

we get the same kind of result as we did for the Car class.
KVC5: Adding valueForKeyPath
Download the code for KVO5. KVO5 looks just like KVO4:

And it does the same thing. The only difference is in the way that AppController accesses the ivars. Here is the new code:

And here is the code from KVO4:

KVO5 uses valueForKeyPath once instead of valueForKey twice. If the user types in "paint", it takes "suv" and "paint" and concatenates them with a period to get "suv.paint" and passes that to keyValueForPath. That path is parsed with the first part being applied to the NSDictionary to get the Vehicle and the second part being passed to the Vehicle to get the ivar. It's all done behind the scenes.

And it does the same thing. The only difference is in the way that AppController accesses the ivars. Here is the new code:

And here is the code from KVO4:

KVO5 uses valueForKeyPath once instead of valueForKey twice. If the user types in "paint", it takes "suv" and "paint" and concatenates them with a period to get "suv.paint" and passes that to keyValueForPath. That path is parsed with the first part being applied to the NSDictionary to get the Vehicle and the second part being passed to the Vehicle to get the ivar. It's all done behind the scenes.
KVC6: A Longer Key Path
KVO6 adds two more ivars for two more vehicles. You can download the code here.

Most of the changes are under the hood. Instead of using an NSDictionary like KVO5 did, KVO6 uses a custom container class called VehicleCollection. VehicleCollection looks like this:

It has two ivars cars and bikes, each storing Vehicles. This adds an extra level of selection to the key path. Notice that the VehicleCollection has no accessors. The -init code looks like this:

Notice that to set up the vehicles it uses setValue:forKey: on the Vehicle class. That's because the Vehicle class doesn't have any accessors to use. This brings up another useful aspect of using KVC: KVC does the release/retain for you. When setValue is used, it takes care of the reference counting automatically, releasing the old object and retaining the new one. Less code to write, debug, and maintain.
The application controller uses an ivar called mytoys to store a pointer to a VehicleCollection:

Now comes the interesting part, accessing the ivars of the Vehicles inside the VehicleCollection. AppController does it this way:

The key path now has three parts. If the user types "paint", then the first ivar access is to cars.suv.paint. This accesses the cars ivar of the mytoys vehicle collection, then the NSDictionary of the VehicleCollection to find the suv object, then the paint ivar of the Vehicle object. All with no accessors. There is no limit to the length of key paths.

Most of the changes are under the hood. Instead of using an NSDictionary like KVO5 did, KVO6 uses a custom container class called VehicleCollection. VehicleCollection looks like this:

It has two ivars cars and bikes, each storing Vehicles. This adds an extra level of selection to the key path. Notice that the VehicleCollection has no accessors. The -init code looks like this:

Notice that to set up the vehicles it uses setValue:forKey: on the Vehicle class. That's because the Vehicle class doesn't have any accessors to use. This brings up another useful aspect of using KVC: KVC does the release/retain for you. When setValue is used, it takes care of the reference counting automatically, releasing the old object and retaining the new one. Less code to write, debug, and maintain.
The application controller uses an ivar called mytoys to store a pointer to a VehicleCollection:

Now comes the interesting part, accessing the ivars of the Vehicles inside the VehicleCollection. AppController does it this way:

The key path now has three parts. If the user types "paint", then the first ivar access is to cars.suv.paint. This accesses the cars ivar of the mytoys vehicle collection, then the NSDictionary of the VehicleCollection to find the suv object, then the paint ivar of the Vehicle object. All with no accessors. There is no limit to the length of key paths.
KVC7: Accessing a Dictionary
Download the code for KVO7. This program is a side step that uses a key path to return a dictionary:

When you enter the ivar name at the top it displays information in one pair of fields or the other depending on whether the vehicle is a car or a bike.
All the changes in this code are in the AppController. It accesses the ivars like this:

Look at the variable d. It is set with a key path that looks like cars.limo. So that returns a dictionary and the rest of the code accesses that dictionary with valueForkey. nil values are returned if the vehicle named is not in the dictionary, so the code uses that to fill in the correct fields of the window.

When you enter the ivar name at the top it displays information in one pair of fields or the other depending on whether the vehicle is a car or a bike.
All the changes in this code are in the AppController. It accesses the ivars like this:

Look at the variable d. It is set with a key path that looks like cars.limo. So that returns a dictionary and the rest of the code accesses that dictionary with valueForkey. nil values are returned if the vehicle named is not in the dictionary, so the code uses that to fill in the correct fields of the window.
KVC8: Accessing An Array
KVO8 is a modified version of KVO6. KVO7 was a side step. In KVO8 fact it looks just like KVO6. Get it at the download page.

In KVO8 the VehicleCollection class has the NSMutableDictionaries replaced with NSMutableArrays:

The code to access the ivars in AppController is different now since the array is indexed:

The first valueForKey is used to access the NSMutableArray ivar by name, either cars or bikes. Then objectAtIndex is used to access the Vehicle in the array, and finally valueForKeyPath accesses the ivar by name. So that is three accesses to get the data.

In KVO8 the VehicleCollection class has the NSMutableDictionaries replaced with NSMutableArrays:

The code to access the ivars in AppController is different now since the array is indexed:

The first valueForKey is used to access the NSMutableArray ivar by name, either cars or bikes. Then objectAtIndex is used to access the Vehicle in the array, and finally valueForKeyPath accesses the ivar by name. So that is three accesses to get the data.
KVC9: Getting An Array
KVC can be used to get an entire array of values at once. Download KVO9 and look at it. KVO9 adds a new ivar, called type:

The VehicleCollection class does away with the two NSMutableArrays and replaces them with one:

and Vehicle now includes the type as an ivar:

These changes mean that AppController can now access an entire array of ivars with a single key path:

Look carefully at what happened there. The key path collection.paint when accessing mytoys returns an array of paint strings, one per Vehicle in the VehicleCollection object. So now KVC is saving us iteration over arrays by doing all the message passing and result collection for us. This works because collection is an NSMutableArray. That's very different from the way that NSMutableDictionaries work on this situation.

The VehicleCollection class does away with the two NSMutableArrays and replaces them with one:

and Vehicle now includes the type as an ivar:

These changes mean that AppController can now access an entire array of ivars with a single key path:

Look carefully at what happened there. The key path collection.paint when accessing mytoys returns an array of paint strings, one per Vehicle in the VehicleCollection object. So now KVC is saving us iteration over arrays by doing all the message passing and result collection for us. This works because collection is an NSMutableArray. That's very different from the way that NSMutableDictionaries work on this situation.
KVC10: Do Some Math
KVO10 adds another ivar and some math to the mix. Download the code and see how KVC can do math for you.

There are the five ivar text fields that were there previously, but now five more are added that do math on the other fields. Doing this used no code, just key paths. AppController implements the functionality like this:

To calculate the sum a key path with a special @sum element is used. So in the example above, the key path is collection.@sum.passengers. That means to get the array referenced by collection and apply the passengers message to each element, then sum the returned values. So this gets the sum of passengers for all the vehicles in the collection.
The other fields work the same way. The only odd one is the count of values. That one uses the key path collection.@count and does not need an ivar name to do its work since it is just counting array elements.
So far I have shown KVO doing the work of accessors, storage management, and math. Saving code, errors, and maintenance. Key paths do more than that, but a visit will be postponed until some other things have been covered.

There are the five ivar text fields that were there previously, but now five more are added that do math on the other fields. Doing this used no code, just key paths. AppController implements the functionality like this:

To calculate the sum a key path with a special @sum element is used. So in the example above, the key path is collection.@sum.passengers. That means to get the array referenced by collection and apply the passengers message to each element, then sum the returned values. So this gets the sum of passengers for all the vehicles in the collection.
The other fields work the same way. The only odd one is the count of values. That one uses the key path collection.@count and does not need an ivar name to do its work since it is just counting array elements.
So far I have shown KVO doing the work of accessors, storage management, and math. Saving code, errors, and maintenance. Key paths do more than that, but a visit will be postponed until some other things have been covered.
The Bagelturf site welcomes Donations of any size