KVC:
1.核心内容:
(1)【对象 setValue:aValue forKey:aKey】;
(2)对象的变量赋值
(3)aValue = 【对象 valueForKey:aKey】;//把变量值取出来
2.举例:
Student *stu = 【【Student alloc】init】;
【stu setValue:@"张三" forKey:@"name"】;//对对象变量赋值
NSString *s1 = 【stu valueForKey:@"name"】;//变量值取出
【stu release】;
KVO:
1.核心内容
(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;
//自动调用监听方法
2.举例
-(void)observerValueForKeyPath:(NSString*)keyPath
ofObject:(id)object
change:(NSDictionary*)change
context:(void*)context
{
NSLog:(@"keyPath:%@ object:%@ change:%@context:%@ ",keyPath,object,change,context);
}
Student *stu = 【【Student alloc】init】;
stu.name = @"张三";
【stu addObserver:self
forKeyPath :@"name"
options:NSKeyValueObservingOptionNew
context:nil】;
stu.name = @"李四";
stu.name = @"王五";
【stu release】;
NSNotification:
1.核心内容
(1)获得通知中心对象
NSNotificationCenter*nc = 【NSNotificationCenter defaultCenter】;
(2)监听通知
【center addObserver :监听者
selector:须执行的方法
name:所监听者通知的名称
object:通知发送者】;
(3)通知中心发布消息
【center PostNotificationName:@“国王万岁”object:某人】;
(4)移除监听中心
2.举例
-(void)test:(NSNtification*)n
{
NSLog(@"name:%@ object:%@ userInfo:%@",【n name】,【n object】,【nuserInfo】);
}
King *king = 【【King alloc】init】;
Farmer *farmer = 【【Farmer alloc】init】;
NSNotificationCenter *center = 【NSNotificationCenter defaultCenter】;
【center addObserver:farmer
selector:@selector(test)
name:@"国王万岁"
object:king】;
【center postNotificationName:@"国王万岁" object:king】;
【center removeObserver:farmer】;
【king release】;
【farmer release】;