UI学习 第十章 KVC    KVO    通知

来源:互联网 发布:人工智能创造新就业 编辑:程序博客网 时间:2024/06/14 10:23

UI学习   第十章                  KVC    KVO    通知

KVC:通过属性的名字进行属性的存和取
存:[ssetValue:@"zhangsan"forKey:@"name"];
取:NSString*str = [s valueForKey:@"name"];
KVO:注册观察者,观察值的改变(注意有值的改变才会调用
-(void)tobeObserver:(Student*)stu{
   
_s = stu;
   
//第一个stu代表被观察对象,第二个self要成为观察者的对象,第三个:被观察者对象属性的名字,第四个代表改变前后的值,最后一个直接设置nil
    [stu
addObserver:selfforKeyPath:@"name"options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOldcontext:nil];
   
    [stu
addObserver:selfforKeyPath:@"age"options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOldcontext:nil];
}
//第一个形参keypath代表被观察者对象属性的名字,通过该参数可以判断是哪个属性发生了改变,参数二:被观察者对象参数三:改变前后的值的字典
-(
void)observeValueForKeyPath:(NSString*)keyPath ofObject:(id)object change:(NSDictionary*)change context:(void*)context{
   
NSLog(@"keypath:%@",keyPath);
   
NSLog(@"object:%@",object);
   
NSLog(@"change:%@",change);
}

-(void)dealloc{
    [_sremoveObserver:selfforKeyPath:@“age”];
    [_sremoveObserver:selfforKeyPath:@"name];
}
通知                      在发送一个通知之前,需保证有监听者,否则此通知无效.m中
例:
校长.m
#import"HeadMaster.h"

@implementationHeadMaster
-(
void)postNote{
   //含参数的通知
    [[NSNotificationCenterdefaultCenter] postNotificationName:@"Meeting" object:@"2015];//校长发布一个要开会的通知(其中的object代表要传的参数)
   
   //含多个参数的
    [[NSNotificationCenterdefaultCenter] postNotificationName:@"feedBack"object:@[@"1",@"3"]userInfo:@{@"a":@"A"}];//校长发布一个评价的通知(object,userInfor代表要传的参数)
}
@end

教师.m
#import"Teacher.h"
@implementationTeacher

-(void)sendNotifi{//老师也发布了一个通知
   //[NSNotificationCenter defaultCenter]获取通知中心,其中NSNotificationCenter是一个单例name代表通知的名字,这个名字用来标识通知,与接受通知的地方保持一致,object代表要传的参数
    [[
NSNotificationCenterdefaultCenter]postNotificationName:@"note"object:nil];
}

-(void)receiveNote{//老师接收了校长的通知
    [[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(meeting:)name:@"Meeting"object:nil];
}
//带参数的通知触发方法
-(void)meeting:(NSNotification *)note{
   NSLog(@"校长喊我开会:%@",note.userInfo);
}

-(
void)dealloc{
   
//移除单个通知
    [[
NSNotificationCenterdefaultCenter]removeObserver:selfname:@"Meeting"object:nil];
}

@end

学生.m
#import"Student.h"

@implementationStudent

-(
void)receiveNotifi{
   
//要成为通知监听者(能够接收某通知),第一步,需要在通知中心添加监听:第一个参数(addObserver:),一般设置为self,需要注册的对象,第二个参数,代表收到通知后调用的方法,第三个参数:代表想要成为哪个通知的监听者,最后一个一般写nil
    [[
NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(study)name:@"note"object:nil];
   
    [[
NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(meeting)name:@"Meeting"object:nil];

    [[
NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(feed:)name:@"feedBack"object:nil];

}

-(
void)study{
   
NSLog(@"我爱学习");
}

-(
void)meeting{
   
NSLog(@"开会");
}

-(
void)feed:(NSNotification*)note{
   
   
id obj = note.object;
   
   
NSLog(@"%@",note.object);
   
NSLog(@"%@",note.userInfo);
}

-(
void)dealloc{
   
//移除所有通知
    [[
NSNotificationCenterdefaultCenter]removeObserver:self];
}

@end

1 0