Changing the key name in NSDictionary

I have a method that returns me an nsdictionary with specific keys and values. I need to change the key names from the dictionary to the new key name, but the values ​​should be the same for this key, but I'm stuck here. Help

+5
source share
4 answers

This method will only work with a mutable dictionary. It does not check what needs to be done if a new key already exists.

You can get a mutable immutable dictionary 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];
    }
}
+7
source

Could you add a new key-value pair using the old value and then delete the old key-value pair?

NSMutableDictionary. NSDictionarys .

0

You cannot change anything in NSDictionary, as it is read-only.

How about looping through a dictionary and creating a new NSMutableDictionary with new key names?

0
source

To change a specific key to a new key, I wrote a recursive method for the 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;
}
0
source

All Articles