KVC:
核心内容:
//对象的变量赋值
【对象 setValue aValueforKey aKey】;
//把变量值取出来
aValue = 【对象 valueForKeyaKey】;
for example:
//当然Student的类已经写好了
Student *stu = 【【Studentalloc】init】;
//对对象变量赋值
【stu setValue:@"王之宝"forKey:@"name"】;
//变量值取出
NSString s1 = 【stuvalueForKey:@"name"】;
//内存的释放不要忘记
【stu release】;
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;
//自动调用监听方法
for example:
-(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 = @"张三";
【stu addObserver: self
forKeyPath:@"name"
options:NSKeyValueObservingOptionNew
context:nil】;
stu.name = @"李四";
stu.name = @"王五";
【stu release】;
NSNotification:
1、获得通知中心对象
NSNotificationCenter*nc =【NSNotificationCenter defaultCenter】;
2、监听通知
【center addObserver :监听者selector:须执行的方法 name:所监听者通知的名称 object:通知发送者】;
3、通知中心发布消息
【centerPostNotificationName:@“国王万岁”object:某人】;
4.移除监听中心
for example:
-(void)test:(NSNtification*)n
{
NSLog(@"name:%@object:%@ userInfo:%@",【n name】,【n object】,【nuserInfo】);
}
King *king = 【【Kingaloc】init】;
Farmer *farmer = 【【Farmeralloc】init】;
NSNotificationCenter *center =【NSNotificationCenter defaultCenter】;
【center addObserver:farmer
selector:@selector(test)
name:@"国王万岁"
object:king】;
【center postNotificationName:@"国王万岁"object:king】;
【centerremoveObserver:farmer】;
【king release】;
【farmer release】;
***********以下为三合一的例子*************
#import <Foundation/Foundation.h>
@interface FRame : NSObject
-(id)initWith;
-(void)printInfo;
@end
#import "FRame.h"
@implementation FRame
-(id)initWith{
self=[super init];
if (self) {
NSNotificationCenter *center;
center=[NSNotificationCenter defaultCenter];
[center addObserver:self
selector:@selector(printInfo)
name:@"tongzhi"
object:nil];
}
return self;
}
-(void)printInfo{
NSLog(@"我已经知道了!");
}
@end
//一下我是在AppDelegate.m中写的东西,只把我写的地方拿出来了
FRame *fr=[[FRame alloc] initWith];
NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
[center postNotificationName:@"tongzhi" object:nil];