Peter ┼átibraný Peter ┼átibraný - 2 years ago 104
Objective-C Question

Why doesn't setValue:forKeyPath invoked on mutable dictionary throw exception for unknown keypaths?

I have following code:

NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[defs setObject:[NSNumber numberWithInt:100] forKey:@"test1.test2.test3"];
[defs setValue:[NSNumber numberWithInt:10] forKeyPath:@"test2.test3.test4"];

I understand that
creates association between "test1.test2.test3" key and given number object. On the other hand,
is Key-Value-Coding method that tries to locate object for path "test2.test3.test4", but in the end, it just silently does nothing. It doesn't even modify the dictionary!

What confuses me greatly is that
doesn't raise any exception nor does it report any error. Why is this? Is this behavior documented anywhere?

Answer Source

I can't find any documentation for this specific case, sorry, but my guess is that this:

[defs setValue:x forKeyPath:@"a.b.c"];

Is being implemented something like this:

[[defs objectForKey:@"a"] setValue:x forKeyPath:@"b.c"];

So objectForKey: returns nil, and methods called on nil just do nothing. That would explain the behaviour you have described.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download