NSString containing just @ ist not Key Value Compliant

531 views Asked by At

Why is a NSString @"@" not Key Value Compliant? Are there other strings that aren't compliant as well?

You can try that it is failing with this code for example:

NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:@"Some Object" forKey:@"@"];

NSString *theObject = [dict valueForKey:@"@"];

Setting it as a key is ok but not querying for that key.. Sure you can work around this error by appending some other string you later on remove another time like doing the following when you want to have the key @:

NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:@"Some Object" forKey:@"keyConst@"];

NSString *theObject = [dict valueForKey:@"keyConst@"];
1

There are 1 answers

1
Martin R On BEST ANSWER

The counterpart to setObject:forKey: is objectForKey: (and not valueForKey:) to retrieve an item from a dictionary:

NSString *theObject = [dict objectForKey:@"@"];

Alternatively, use the "new" dictionary subscripting syntax:

dict[@"@"] = @"Some Object";
NSString *theObject = dict[@"@"];

valueForKey: uses Key-Value coding methods if the key starts with @. From the documentation of -[NSDictionary valueForKey:]:

If key does not start with “@”, invokes objectForKey:. If key does start with “@”, strips the “@” and invokes [super valueForKey:] with the rest of the key.

For example,

NSString *x = [dict valueForKey:@"@description"];

does the same as

NSString *x = [dict description];

So in almost all cases, you should use objectForKey:, unless you explicitly want to do some Key-Value coding magic.