KVO,即:Key-Value Observing,它提供一種機(jī)制,當(dāng)指定的對(duì)象的屬性被修改后,則對(duì)象就會(huì)接受到通知。簡(jiǎn)單的說(shuō)就是每次指定的被觀察的對(duì)象的屬性被修改后,KVO就會(huì)自動(dòng)通知相應(yīng)的觀察者了。
定義一個(gè)類A
@interface A : NSObject {
int age;
}
@end
2.定義此A為Controller的屬性,實(shí)例化它,監(jiān)聽(tīng)它的屬性,并顯示在當(dāng)前的View里邊
- (void)viewDidLoad
{
[super viewDidLoad];
a = [[A alloc] init];
a.age = 5;
[a addObserver:self forKeyPath:@"age" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:NULL];
myLabel = [[UILabel alloc]initWithFrame:CGRectMake(100, 100, 100, 30 )];
myLabel.textColor = [UIColor redColor];
myLabel.text = [NSString StringWithFormat:@"%d",a.age];
[self.view addSubview:myLabel];
UIButton * b = [UIButton buttonWithType:UIButtonTypeRoundedRect];
b.frame = CGRectMake(0, 0, 100, 30);
[b addTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:b];
}
3.當(dāng)點(diǎn)擊button的時(shí)候,調(diào)用buttonAction方法,修改對(duì)象的屬性
-(void) buttonAction
{
a.age += 5;
}
4.實(shí)現(xiàn)回調(diào)方法
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if([keyPath isEqualToString:@"age"])
{
[NSString StringWithFormat:@"%d",a.age];
}
}
5.最后當(dāng)頁(yè)面退出時(shí)需remove觀察者
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注