开发者

Is an NSMutableDictionary key-value compliant for every key?

I need to set some observers on a lot of different keys and I'd rather not declare about fifty different @properties, (as I had started to do) so I'm wondering if NSDictionary can do it all for me?

Update

Guess I should be more specific, I would like to be able to set objects for arbitrary keys (NSStrings) in an NSMutableDictionary, then also registerObserver for arbitrary keys in the same dictionary, regardless of whether the key has ever been set before in that dict. Does an NSMutableDictionary work this way "out of the box"? or do I need to make a container class with overridden setValue:forKey: ?

Update 2

I threw together this quick test and it looks promising. Using SenTestingKit here to test.

//My dictionary
NSMutableDictionary * myDict = [[NSMutableDictionary alloc] init];

//An object that does 开发者_高级运维not respond to notifications, and will therefore throw exceptions
NSNumber * notKVOcompliant = [NSNumber numberWithInt:1];

//Adding that object as an observer...
[myDict addObserver:notKVOcompliant forKeyPath:@"five" options:NSKeyValueObservingOptionNew context:nil];

//causing a notification to fire, which causes an exception to throw.
STAssertThrows([myDict setObject:@"something" forKey:@"five"],@"Notification was not sent.");

//A control group, to make sure the exception is because of the specific observed key
STAssertNoThrow([myDict setObject:@"something" forKey:@"six"], @"Control group");

//and lastly a manufactured failure to make sure this test has run
STFail(@"Ensure this test is running");

So I ran that, and it seems like it actually DOES work out of the box. The NSNumber as an observer must be getting the notification, which causes it to throw an unrecognized selector exception, which causes STAssertThrows to pass.

The other key has no observers, and therefore no effect.

The STFail is failing, which means the test is for sure running.


Yes, it is. A normal un-subclassed NSMutableDictionary delivers KVO notifications for any NSString key that is subscribed to, when the key is changed with setValue:forKey:

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜