@interface Walker : NSObject
{
NSInteger _age;
NSString *_name;
}
@property (nonatomic) NSInteger age;
@property (nonatomic, retain) NSString *name;
- (id)initWithName:(NSString *)name age:(NSInteger)age;
``
import “Walker.h”
@implementation Walker
- (id)initWithName:(NSString *)name age:(NSInteger)age
{
if (self = [super init]) {
_name = name;
_age = age;
}
return self;
}
@end
import
- (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属性发生变化,就会调用此函数*/
- (void)observeValueForKeyPath:(NSString )keyPath ofObject:(id)object change:(NSDictionary )change context:(void *)context
{
NSLog(@”keyPath = %@ \nobject =%@ \nchange = %@ \n”, keyPath,object,change);
if ([keyPath isEqualToString:@”age”] && object == _walker) {
_ageLabel.text = [NSString stringWithFormat:@”%@现在的年龄是: %ld”, _walker.name, (long)_walker.age];
}
}
如下图:
“`
- (void)observeValueForKeyPath:(NSString )keyPath ofObject:(id)object change:(NSDictionary )change context:(void *)context
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-07 16:23:05