Cocoa key value observing a key/entry in a dictionary

后端 未结 1 2001
春和景丽
春和景丽 2021-02-19 01:51

Is it possible to observe a specific key in a dictionary? If so how can I do it?

1条回答
  •  误落风尘
    2021-02-19 02:40

    Yes (although it only makes sense to be observing an NSMutableDictionary).

    @interface Foo : NSObject @end
    @implementation Foo 
    
    - (void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
        NSLog(@"observing: -[%@ %@]", object, keyPath);
        NSLog(@"change: %@", change);
    }
    
    @end
    
    int main (int argc, const char * argv[]) {
        NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    
        Foo * f = [[Foo alloc] init];
    
        NSMutableDictionary * d = [NSMutableDictionary dictionary];
        [d addObserver:f forKeyPath:@"foo" options:0 context:NULL];
        [d setObject:@"bar" forKey:@"foo"];
        [d removeObjectForKey:@"foo"];
        [d removeObserver:f forKeyPath:@"foo"];
        [f release];
    
        [pool drain];
        return 0;
    }
    

    Logs:

    2010-12-21 17:39:53.758 EmptyFoundation[94589:a0f] observing: -[{
        foo = bar;
    } foo]
    2010-12-21 17:39:53.764 EmptyFoundation[94589:a0f] change: {
        kind = 1;
    }
    2010-12-21 17:39:53.765 EmptyFoundation[94589:a0f] observing: -[{
    } foo]
    2010-12-21 17:39:53.765 EmptyFoundation[94589:a0f] change: {
        kind = 1;
    }
    

    0 讨论(0)
提交回复
热议问题