NSDictionary keys with @ symbol

て烟熏妆下的殇ゞ 提交于 2020-02-25 05:33:00

问题


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.


回答1:


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.




回答2:


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"]);


来源:https://stackoverflow.com/questions/17670240/nsdictionary-keys-with-symbol

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!