码迷,mamicode.com
首页 > 其他好文 > 详细

KVO 小探

时间:2015-06-29 11:24:01      阅读:115      评论:0      收藏:0      [点我收藏+]

标签:

#import "ViewController.h"

@interface ViewController ()

  @property (copy, nonatomicNSString *name;

  @property (assign, nonatomic) NSInteger age;

 或者你这样

{

    NSString *_name;

    NSInteger _age;

}

@end

 

@implementation ViewController

 

- (void)viewDidLoad {

    [super viewDidLoad];

    SCViewController *svc = [[SCViewController alloc]init];

    //ViewController对象监听SCViewController对象的属性变化,那么该是这样

 //【被观察对象】 addObserver:【观察者】 forKeyPath:【被观察对象属性】 options:【选项 new or old】 context:【内容】;   其中【被观察对象属性】这个不能有下划线,无论你用@property声明属性或者用{}声明一个带下划线的成员变量。注册和移除要成对出现。。

    [ svc addObserver:self forKeyPath:@"h" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:@"me"];//为svc注册一个观察者是ViewController对象的kvo

    [svc setValue:@7 forKey:@"h"];

    [svc removeObserver:self  forKeyPath:@"h"];//移除kvo

}

//触发kvo后的回调方法

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {

     NSLog(@"%@", keyPath);

     NSLog(@"%@", change);

     NSLog(@"%@", object);

     NSLog(@"%@", context);

}

 

 

- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

 

@end

KVO 小探

标签:

原文地址:http://www.cnblogs.com/plummithly/p/4606916.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!