iphone66
iphone66

Reputation: 144

changing a key name in NSDictionary

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

Upvotes: 6

Views: 5275

Answers (4)

Samdrain
Samdrain

Reputation: 433

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;
}

Upvotes: 1

Twelve47
Twelve47

Reputation: 3984

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.

Upvotes: 0

Nick Weaver
Nick Weaver

Reputation: 47231

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];
    }
}

Upvotes: 7

Bastian
Bastian

Reputation: 10433

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 ?

Upvotes: 0

Related Questions