Key-value coding (KVC) is a mechanism that allows you to set and get the value of a variable by its name. The name is simply a string,but we refer to that name as a key. So,for example,imagine that you have a class called Student that has an instance variable called firstName of type Nsstring:
If you had an instance of Student,you Could set its firstName like this:
You Could read the value of its Nsstring *x = [s valueForKey:@"firstName"];
The methods setValue:forKey: and valueForKey: are defined in NSObject. Even though this doesn't look like rocket science,the ability to read and set a variable by its name is really powerful. The rest of this chapter will be a simple example that should illustrate some of that power.
一、Key-Value Coding
In Xcode,create a new project of type Cocoa Application. Name the project KVCFun. In the project,create a new file of typeObjective-C Class. Name the class AppController.
At this point in our exploration of key-value coding,you simply need an instance of AppController to be created with theMainMenu.nib file read in. Drag out a custom object and set its class to be AppController (Figure 7.1).
figure 7.1. Create AppController
Save the nib file.
Back in Xcode,open AppController.h,and add an instance variable called fido of type int:
In AppController.m,you are going to create an init method that sets and reads fido by using key-value coding. This is a bit silly because it is going to be a long-winded way to get a simple result. This is designed to be illustrative rather than practical.
What makes the method so long-winded is that the key-value coding methods work with objects,so instead of passing an intNSNumber. Add this method to AppController.m:
The key-value coding mechanism will automatically convert the NSNumber to an int before using it to set the value of fido. Build and run the application,but don't expect much. When the blank window appears, "fido = 5" will be logged to the console.
If you have accessor methods for getting and setting fidofidosetFido:. Note that this is more than simply a convention; if you give your accessors nonstandard names,they will not get called by the key-value coding methods. Add fido and setFido: to- (int)fido { NSLog(@"-fido is returning %d",fido); return fido; } - (void)setFido:(int)x { NSLog(@"-setFido: is called with %d",x); fido = x; }
Declare these methods in AppController.h:
Build and run the application. Note that your accessor methods are being called.
二、Bindings
Many graphical objects in Cocoa have bindings. When you bind a key,such as fidofido Open MainMenu.nib. Drop a slider on the window. In the Attributes Inspector,make the slider Continuous (Figure 7.2).
Figure 7.2. Make Slider Continuous[View full size image]
In the Bindings Inspector,bind the value of the slider to the fido key of the instance of figure 7.3).
Figure 7.3. Bind Value of Slider to fido[View full size image]