Using valueForKeyPath on NSDictionary if a key starts the @ symbol?

Viewed 22387

I want to use valueForKeyPath on my NSDictionary, but the problem is that one of the keys is a string that starts with the @ symbol. I have no control over the naming of the key.

I'm having problems trying to create the key path as I'm getting a format exception, even when trying to escape the @ symbol:

This works fine:

[[[dict objectForKey:@"key1"] objectForKey:@"@specialKey"] objectForKey:@"key3"]

However none of these work:

[dict valueForKeyPath:@"key1.@specialKey.key3"]
[dict valueForKeyPath:@"key1.@@specialKey.key3"]

Any ideas?

Thanks,

Mike

5 Answers

In my humble opinion, the whole discussion here goes the wrong way Accessing entries in an NSDictionary via key paths - is simply not part of KVC protocol.

KVC defines how to name your properties of an object, so that KVC can work. an entry in an NSDictionary is not a property, and has no name. NSDictionary adds its bit of magic to the KVC-like behaviour, by "pretending" the keys of its entries are like 'properties' of the dictionary.

Alas, properties have different naming conventions and limitations than dictionary keys.

If you cannot force the dictionary keys to conform with KVC-supported property names - break your key paths, and use the accessors instead where in doubt.

That, I think, should be the safest way to go. KVC is generally a "nicety" being able to shorten your code - but it does NOT provide any functionality you cannot have otherwise (as you demonstrated yourself).

Related