views:

607

answers:

2

Hi there,

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:@"[email protected]"]
[dict valueForKeyPath:@"key1.@@specialKey.key3"]

Any ideas?

Thanks,

Mike

+4  A: 

you shouldn't be using @ signs with your key names if you want to use key value coding.

apple's guidelines for key names are as follows:

Keys must use ASCII encoding, begin with a lowercase letter, and may not contain whitespace.

You'll have to find a workaround to reformat the key string whereever you're getting your keys from to be KVC compliant.

pxl
Ah okay then! I thought some form of escaping needed to happen but thinking about it, of course something starting with @ can't be KVC compliant! Cheers!
Michael Waterfall
np. it'll also save you a lot of headache when you use other classes and technologies that use KVC, like core data.
pxl
A: 

If you have no control over the naming, how about adding a category with a properly named key that simply returns/sets the weird key?

Kendall Helmstetter Gelner
that's a good idea. but given what KVC is supposed to do, i don't see how that is even necessary. KVC is a practice of sorts to make naming getters and setters consistently so you can access properties. so if you can't name a property with an @ sign in it, then you should never get into a situation where it'd be a part of a keypath either.
pxl