本文主要是介绍KVO(2),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
@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:selfaction:@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
这篇关于KVO(2)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!