标签:kvo
@interface Walker : NSObject
{
NSInteger _age;
NSString *_name;
}
@property (nonatomic) NSInteger age;
@property (nonatomic, retain) NSString *name;
- (id)initWithName:(NSString *)name age:(NSInteger)age;
``
@implementation Walker
(void)viewDidLoad {
[super viewDidLoad];
_walker = [[Walker alloc] initWithName:@”LJF” age:25];
NSLog(@”%ld”, (long)_walker.age);
/* 关键步骤 */
[_walker addObserver:self
forKeyPath:@”age”
options:NSKeyValueObservingOptionNew
context:nil];
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
[btn setFrame:CGRectMake(120, 200, 100, 35)];
[btn setBackgroundColor:[UIColor lightGrayColor]];
[btn setTitle:@"增加5岁" forState:UIControlStateNormal];
[btn addTarget:self
action:@selector(buttonPressed)
forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
_ageLabel = [[UILabel alloc] initWithFrame:CGRectMake(40, 150, 200, 35)];
_ageLabel.text = [NSString stringWithFormat:@"%@现在的年龄是: %ld", _walker.name, (long)_walker.age];
_ageLabel.backgroundColor = [UIColor clearColor];
[self.view addSubview:_ageLabel];
}
(void)buttonPressed
{
_walker.age += 5;
}
/* KVO function, 只要object的keyPath属性发生变化,就会调用此函数*/
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:kvo
原文地址:http://blog.csdn.net/tubiebutu/article/details/46699371