KVC
Key-Value-Coding
直白了就是键值对的意思。先拿到某个对象,知道对象中某个属性的名称,可以根据这个名称来获取这个对象属性的值。也可以重新设置这个对象属性的值。是不是感觉很熟悉
,就好像是 对象.属性 (person.age)这样获取这个数据。还可以设置此属性的数据。
NSString *originalName = [p valueForKey:@
"name"
];
// using the KVC accessor (setter) method.
[p setValue:newName forKey:@
"name"
];
NSLog(@
"Changed %@'s name to: %@"
, originalName, newName);
KVO
就是对某个对象,中的某个属性添加观察,好像观察者一样,只要发现这对象的属性值变化了,就告诉某个方法
Key-Value Observing (KVO) 建立在 KVC 之上,它能够观察一个对象的 KVC key path 值的变化。举个例子,用代码观察一个 person 对象的 address 变化,以下是实现的三个方法:
- watchPersonForChangeOfAddress: 实现观察
- observeValueForKeyPath:ofObject:change:context: 在被观察的 key path 的值变化时调用。
- dealloc 停止观察
-(
void
) watchPersonForChangeOfAddress:(Person *)p
{
// this begins the observing
[p addObserver:self
forKeyPath:@
"address"
options:0
context:KVO_CONTEXT_ADDRESS_CHANGED];
// keep a record of all the people being observed,
// because we need to stop observing them in dealloc
[m_observedPeople addObject:p];
}
// whenever an observed key path changes, this method will be called
- (
void
)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(
void
*)context
{
// use the context to make sure this is a change in the address,
// because we may also be observing other things
if
(context == KVO_CONTEXT_ADDRESS_CHANGED) {
NSString *name = [object valueForKey:@
"name"
];
NSString *address = [object valueForKey:@
"address"
];
NSLog(@
"%@ has a new address: %@"
, name, address);
}
}
-(
void
) dealloc;
{
// must stop observing everything before this object is
// deallocated, otherwise it will cause crashes
for
(Person *p in m_observedPeople){
[p removeObserver:self forKeyPath:@
"address"
];
}
[m_observedPeople release];
m_observedPeople = nil;
[super dealloc];
}
-(id) init;
{
if
(self = [super init]){
m_observedPeople = [NSMutableArray
new
];
}
return
self;
}
@end