Mac开发学习_3

Key-Value Coding; Key-Value Observing

In Xcode, create a new project of type Cocoa Application. Name the project KVCFun. In the project, create a new file of type Objective-C Class. Name the class AppController.

At this point in our exploration of key-value coding, you simply need an instance of AppControllerto be created with the MainMenu.nib file read in. Drag out a custom object and set its class to beAppController (Figure 7.1).

Save the nib file.

Back in Xcode, open AppController.h, and add an instance variable called fido of type int:

@interface AppController : NSObject
{
    int fido;
}
@end

 

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 int, you will need to create an NSNumber. Add this method toAppController.m:

- (id)init
{
    [super init];
    [self setValue:[NSNumber numberWithInt:5]
            forKey:@"fido"];
    NSNumber *n = [self valueForKey:@"fido"];
    NSLog(@"fido = %@", n);
    return self;
}

 

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 fido, they will be used. You must, however, give them the correct names. The getter must be called fido, and the setter must be calledsetFido:. 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: toAppController.m:

- (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:

- (int)fido;
- (void)setFido:(int)x;

 

Build and run the application. Note that your accessor methods are being called.

posted on 2012-04-23 22:18  Rogo_s_Blog  阅读(202)  评论(0编辑  收藏  举报

导航