KVC:
核心内容:
//对象的变量赋值
【对象setValueaValueforKeyaKey】;
//把变量值取出来
aValue=【对象valueForKeyaKey】;
forexample:
//当然Student的类已经写好了
Student*stu=【【Studentalloc】init】;
//对对象变量赋值
【stusetValue:@"王之宝"forKey:@"name"】;
//变量值取出
NSStrings1=【stuvalueForKey:@"name"】;
//内存的释放不要忘记
【sturelease】;
KVO:
1、注册监听
【被监听对象addObserver监听者forKeyPath被监听对象的属性options监视内容(新值或旧值)context额外信息】;
2、监听者实现的方法
-(void)observerValueForKeyPath:(NSString*)keyPath
ofObject:(id)object(被监听对象)
change:(NSdictionary*)change
context:(void*)context(可以理解为参数){
NSLog(@“keyPath:%@object:%@change:%@context:%@”,keyPath,object,change,context);
}
3、监听触发条件
//被监听对象key=newValue;
//自动调用监听方法
forexample:
-(void)observerValueForKeyPath:(NSString*)keyPath
ofObject:(id)object
change:(NSDictionary*)change
context:(void*)context{
NSLog:(@"keyPath:%@object:%@change:%@context:%@",keyPath,object,change,context);
}
Student*stu=【【Studentalloc】init】;
stu.name=@"张三";
【stuaddObserver:self
forKeyPath:@"name"
options:NSKeyValueObservingOptionNew
context:nil】;
stu.name=@"李四";
stu.name=@"王五";
【sturelease】;
NSNotification:
1、获得通知中心对象
NSNotificationCenter*nc=【NSNotificationCenterdefaultCenter】;
2、监听通知
【centeraddObserver:监听者selector:须执行的方法name:所监听者通知的名称object:通知发送者】;
3、通知中心发布消息
【centerPostNotificationName:@“国王万岁”object:某人】;
4.移除监听中心
forexample:
-(void)test:(NSNtification*)n
{
NSLog(@"name:%@object:%@userInfo:%@",【nname】,【nobject】,【nuserInfo】);
}
King*king=【【Kingaloc】init】;
Farmer*farmer=【【Farmeralloc】init】;
NSNotificationCenter*center=【NSNotificationCenterdefaultCenter】;
【centeraddObserver:farmer
selector:@selector(test)
name:@"国王万岁"
object:king】;
【centerpostNotificationName:@"国王万岁"object:king】;
【centerremoveObserver:farmer】;
【kingrelease】;
【farmerrelease】;
***********以下为三合一的例子*************
#import<Foundation/Foundation.h>
@interfaceFRame:NSObject
-(id)initWith;
-(void)printInfo;
@end
#import"FRame.h"
@implementationFRame
-(id)initWith{
self=[superinit];
if(self){
NSNotificationCenter*center;
center=[NSNotificationCenterdefaultCenter];
[centeraddObserver:self
selector:@selector(printInfo)
name:@"tongzhi"
object:nil];
}
returnself;
}
-(void)printInfo{
NSLog(@"我已经知道了!");
}
@end
//一下我是在AppDelegate.m中写的东西,只把我写的地方拿出来了
FRame*fr=[[FRamealloc]initWith];
NSNotificationCenter*center=[NSNotificationCenterdefaultCenter];
[centerpostNotificationName:@"tongzhi"object:nil];