Key-value coding(KVC)机制允许set(设置)和get(获取)变量值。这里的变量名可能是一个字符串,也就是Key。例如,类Company拥有一个类型为NSString,叫做companyName的变量。
@interface Company : NSObject
{
NSString *companyName;
}
我们就可以这样设置和获取Company实例的companyName值:
//设置值
Company *company = [[Company alloc] init];
[company setValue:@"Apple" forkey:@"companyName"];
//获取值
NSString *x = [company valueForKey:@"companyName"];
实例setValue:forKey和valueForKey:的方法在NSObject中有定义。
创建名为KVCFun的项目,新建名为AppController的Objective-C Class文件。
AppController.h和AppController.m的代码分别如下:
#import <Foundation/Foundation.h>
@interface AppController : NSObject {
@private
int fido;
}
- (int) fido;
- (void) setFido:(int) x;
- (IBAction) incrementFido: (id)sender;
@end
#import "AppController.h"
@implementation AppController
- (id)init
{
self = [super init];
if (self) {
//设置Key
[self setValue:[NSNumber numberWithInt:5]
forKey:@"fido"];
NSNumber *n = [self valueForKey:@"fido"];
NSLog(@"fido = %@", n);
}
return self;
}
- (int) fido
{
NSLog(@"-fido is returning %d", fido);
return fido;
}
- (void) setFido:(int) x
{
NSLog(@"-setFido is called with %d", x);
fido = x;
}
- (IBAction) incrementFido:(id)sender
{
//当直接修改值时,通知观察者
[self willChangeValueForKey:@"fido"];
fido++;
NSLog(@"fido is now %d", fido);
[self didChangeValueForKey:@"fido"];
}
- (void)dealloc
{
[super dealloc];
}
@end
打开MainMenu.nib,添加一个Slider、一个Label、一个Button控件,如下图:
将Slider的Attributes Inspector->Control->State设为“连续的”,再把Binding Inspector->value邦定到AppController实例的fido key上。
将Label也邦定到AppController上,Model Key Path设为fido。
Button链接到incrementFido:action上。
@property和@synthesize
我们可以使用property来代替fido和setFido,并且使用synthesize来实现存取方法。
使用下面的代码替换AppController.h中的fido和setFido:
@property (readwrite, assign) int fido;
使用@synthesize来替换fido和setFido,程序可以正常运行。