ios

KVO 与 KVC

2016-05-07  本文已影响28人  武一顶顶

void changeName(Person *p, NSString *newName)
{
 
    // using the KVC accessor (getter) method
    NSString *originalName = [p valueForKey:@"name"];
 
    // using the KVC  accessor (setter) method.
    [p setValue:newName forKey:@"name"];
 
    NSLog(@"Changed %@'s name to: %@", originalName, newName);
 
}
   // 现在,如果 Person 有另外一个 key 配偶(spouse),spouse 的 key 值是另一个 Person 对象,用 KVC 可以这样写:


void logMarriage(Person *p)
{
 
    // just using the accessor again, same as example above
    NSString *personsName = [p valueForKey:@"name"];
 
    // this line is different, because it is using
    // a "key path" instead of a normal "key"
    NSString *spousesName = [p valueForKeyPath:@"spouse.name"];
 
    NSLog(@"%@ is happily married to %@", personsName, spousesName);
 
}
    key 与 key pat 要区分开来,key 可以从一个对象中获取值,而 key path 可以将多个 key 用点号 “.” 分割连接起来,比如:

[p valueForKeyPath:@"spouse.name"];
相当于这样……

[[p valueForKey:@"spouse"] valueForKey:@"name"];
  //好了,以上是 KVC 的基本知识,接着看看 KVO。
static NSString *const KVO_CONTEXT_ADDRESS_CHANGED = @"KVO_CONTEXT_ADDRESS_CHANGED"
 
@implementation PersonWatcher
 
-(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

*/

//setValue:obj forKeyPath:setValue:obj forKeyPath:
//1.先去看有没有跟key值相同的成员属性,如果有,就会调用该成员属性的set方法,给该成员属性赋值.
//2.如果没有跟它相同的成员属性的set方法, 会直接给该属性赋值.
//3.还会去判断有没有跟它相同名称,并且带有下划线的成员属性.如果有,就给该属性赋值.
//4.如果没有带有下划线的成员属性,就会直接报错.

上一篇 下一篇

猜你喜欢

热点阅读