문제

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@"];
도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top