#import "ViewController.h"
@interface ViewController ()
@property (copy, nonatomic) NSString *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