changing a key name in NSDictionary

烂漫一生 提交于 2019-12-06 03:38:37

问题


I have a method which returns me a nsdictionary with certain keys and values. i need to change the key names from the dictionary to a new key name but the values need to be same for that key,but i am stuck here.need help


回答1:


This method will only work with a mutable dictionary. It doesn't check what should be done if the new key already exists.

You can get a mutable dictionary of a immutable by calling mutableCopy on it.

- (void)exchangeKey:(NSString *)aKey withKey:(NSString *)aNewKey inMutableDictionary:(NSMutableDictionary *)aDict
{
    if (![aKey isEqualToString:aNewKey]) {
        id objectToPreserve = [aDict objectForKey:aKey];
        [aDict setObject:objectToPreserve forKey:aNewKey];
        [aDict removeObjectForKey:aKey];
    }
}



回答2:


You can't change anything in an NSDictionary, since it is read only.

How about loop through the dictionary and create a new NSMutableDictionary with the new key names ?




回答3:


Could you not add a new key-value pair using the old value, and then remove the old key-value pair?

This would only work on an NSMutableDictionary. NSDictionarys are not designed to be changed once they have been created.




回答4:


To change specific key to new key, I have written a recursive method for Category Class.


- (NSMutableDictionary*)replaceKeyName:(NSString *)old_key with:(NSString )new_key {
    NSMutableDictionary dict = [NSMutableDictionary dictionaryWithDictionary: self];
    NSMutableArray *keys = [[dict allKeys] mutableCopy];
    for (NSString key in keys) {
        if ([key isEqualToString:old_key]) {
            id val = [self objectForKey:key];
            [dict removeObjectForKey:key];
            [dict setValue:val forKey:new_key];
            return dict;
        } else {
            const id object = [dict objectForKey: key];
            if ([object isKindOfClass:[NSDictionary class]]) {
                [dict setObject:[dict replaceKeyName:old_key with:new_key] forKey:key];
            } else if ([object isKindOfClass:[NSArray class]]){
                if (object && [(NSArray)object count] > 0) {
                    NSMutableArray *arr_temp = [[NSMutableArray alloc] init];
                    for (NSDictionary *temp_dict in object) {
                        NSDictionary *temp = [temp_dict replaceKeyName:old_key with:new_key];
                        [arr_temp addObject:temp];
                    }
                    [dict setValue:arr_temp forKey:key];
                }
            }
        }
    }
    return dict;
}


来源:https://stackoverflow.com/questions/5632275/changing-a-key-name-in-nsdictionary

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