KVC:
BookData *bookData=[[BookData alloc]init];
[bookData setValue:@"天数" forKey:@"name"];
[bookData setValue:@"22.0f" forKey:@"price"];
NSString *s=[bookData valueForKey:@"name"];
id price1=[bookData valueForKey:@"price"];
float price2=[[bookData valueForKey:@"price"]floatValue];
NSLog(@"price1===%@",price1);
//float pr=(float)price1;还不可以强制转换。
NSLog(@"price2===%f",price2);
NSLog(@"s===%@",s);
本类监听:
-(id)initWithName:(NSString *)name1 andAge:(NSString *)age1{
self=[super init];
if (self) {
name=name1;
age=age1;
//注册监听
[self addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew context:nil];
}
return self;
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
NSLog(@"object===%@,change===%@",[object description],change);
}
控制台:
2012-08-22 20:18:05.797 Student[3108:707] object===<Student: 0x100114310>,change==={
kind = 1;
new = xiaoming;
}
跨类通知:
发送通知方:
- (void)getIT{
//发出通知
[[NSNotificationCenter defaultCenter] postNotificationName:@"notice" object:self ];
NSLog(@"get it.");
接受通知方:
-(id)init{
self=[super init];
if (self) {
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(callBack) name:@"notice" object:nil];
}
return self;
}
- (void)callBack{
NSLog(@"i am back.");
}
-(void)dealloc{
//移除监听者
[[NSNotificationCenter defaultCenter] removeObserver:self];
[super dealloc];
}
main.m:
King *k=[[King alloc]initWithName:@"guowang1"];
Worker *w=[[Worker alloc]init];
[k getIT];
控制台:
2012-08-22 20:21:06.721 Student[3136:707] i am back.
2012-08-22 20:21:06.732 Student[3136:707] get it.
监听,通知kvc ,kvo
最新推荐文章于 2023-05-14 12:18:38 发布