KVC && KVO 初见

image

Look,这是一个很简单的要求,点击Add me,age +1.

想一想的话很简单的,设置一个属性Nsinteger age,点击button add me,直接加1在重新显示Lable就好啦,不过,我们今天是来练习KVC和KVO的,苹果的键值编程哈哈

首先我们定义一个Human的类,并且完成了它的初始化方法

#import <Foundation/Foundation.h>

@interface human : NSObject

@property (nonatomic,assign) NSString *name;
@property (nonatomic,assign) NSInteger age;
-(id)initHuman:(NSString *)Initname hisage:(NSInteger) Initage;
@end
#import "human.h"

@implementation human
-(id)initHuman:(NSString *)Initname hisage:(NSInteger)Initage{
    if(self=[super init]){
        _name=Initname;
        _age=Initage;
       
    }
    return self;
}

@end

很普通很简单。。。

下面在ViewControler中调用该类,完成对这个人的年龄的增加

#import <UIKit/UIKit.h>
#import "human.h"
@interface ViewController : UIViewController<UIWebViewDelegate>
{
    human *keith;
}
@property (weak, nonatomic) IBOutlet UILabel *Infoshow;
- (IBAction)Addme:(id)sender;
@end
#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];   
    keith=[[human alloc]initHuman:@"keith" hisage:26];
    self.Infoshow.text=[NSString stringWithFormat:@"name is %@,age is %ld",keith.name,keith.age];
    [keith addObserver:self forKeyPath:@"age" options:NSKeyValueObservingOptionOld|NSKeyValueObservingOptionNew context:nil];//
}
- (IBAction)Addme:(id)sender {
    keith.age+=1;      
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    if ([keyPath isEqualToString:@"age"] && object==keith) {
          self.Infoshow.text=[NSString stringWithFormat:@"name is %@,age is %ld",keith.name,keith.age];//添加对keith keyPath的监视
    }
}
-(void)dealloc{
    [keith removeObserver:self forKeyPath:@"age"];//不用的时候移除注册
}

@end

可以看出如果通过这样的模式有个好处是能减少模型和视图的耦合关键,模型只管运算,视图的变化通过KVO监视键值的变化,自动更新。

posted @ 2014-11-25 17:44  KeithMorning  阅读(261)  评论(0编辑  收藏  举报