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,程序可以正常运行。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。