![](/img/trans.png)
[英]How to check if an NSMutableDictionary contains Value (not Key) in iOS?
[英]Key Value Observing a key in an NSMutableDictionary that contains dots?
我想使用KVO來觀察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;
}
但是,這不起作用:
@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:@"com.company.foo" options:0 context:NULL];
[d setObject:@"bar" forKey:@"com.company.foo"];
[d removeObjectForKey:@"com.company.foo"];
[d removeObserver:f forKeyPath:@"com.company.foo"];
[f release];
[pool drain];
return 0;
}
由於無法在帶有KVO的NSDictionary
中的鍵中使用點,您可以改為使用點語法對字符串進行哈希處理,並將其用於鍵。 這將提供唯一可識別的密鑰,同時保留點語法 - 盡管有一些散列/去散列開銷。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.