1

Like asked here before Using valueForKeyPath on NSDictionary if a key starts the @ symbol?

If i have to use NSDictionary with keys like "@ID" and "@Name" (Server side limitations,I have no control over the naming) how can i work around that? Right now the app just crash every time I'm trying to access to this kind of keys.

Community
  • 1
  • 1
ItayAmza
  • 819
  • 9
  • 21
  • I'm not totally sure what you're doing, can you show the code where the problem is occurring? – Ander Jul 16 '13 at 07:20

2 Answers2

0

As already stated you cannot do this. To Paraphrase Apple Docs reg. Key format -

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

So trying to have a key with @.. as start isn't going to cut it. What I suggest you do is this - since you cannot change the way your backend sends the keys, you can control how those keys are represented in iOS. So Once you get the keys remove the starting @ symbol and insert the rest of the string as key. Since @ is constant across all keys, removing them from all keys should not affect cardinality of your dict.

Srikar Appalaraju
  • 71,928
  • 54
  • 216
  • 264
  • Thans, but how can i remove it when i cannot access this keys? when i print [MyDict allKeys] the app crashes too. – ItayAmza Jul 16 '13 at 07:31
  • 1
    before populating `MyDict` process your keys which you got from your server and then populate `MyDict` with the new keys... Is that clear? – Srikar Appalaraju Jul 16 '13 at 07:36
  • Yes I'll do that, Thanks. – ItayAmza Jul 16 '13 at 07:39
  • @ItayAmza, I think there is way to handle the situation at your side. check my answer, please. – holex Jul 16 '13 at 07:44
  • I also experienced this issue when @ was used in the beginning of the key - not in the middle or end. The obvious solution was to use a string replace on '@' to e.g. '(a)'. When I tried to break it again with other "odd" characters, numbers, uppercase or lower, I failed. – kjoelbro Apr 09 '15 at 09:32
0

what if you try to convert the dictionary after you get it with the irregular keys?

the idea would be this, and yes, it is thread-safe:

NSDictionary *_dictionary = [NSDictionary dictionaryWithObjectsAndKeys:@"value", @"@ID", @"value2", @"@Name", nil];

NSMutableDictionary *_mutableDictionary = [NSMutableDictionary dictionary];
NSLock *_lock = [[NSLock alloc] init];
[_dictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
    if ([_lock tryLock]) {
        NSString *_newKey = [key stringByReplacingOccurrencesOfString:@"@" withString:@""];
        [_mutableDictionary setValue:obj forKey:_newKey];
        [_lock unlock];
    }
}];

NSLog(@"ID : %@", [_mutableDictionary valueForKey:@"ID"]);
NSLog(@"Name : %@", [_mutableDictionary valueForKey:@"Name"]);
holex
  • 23,961
  • 7
  • 62
  • 76