cocoa's Key-value coding

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,程序可以正常运行。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值