开发者

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 开发者_JAVA技巧that key,but i am stuck here.need help


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


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 ?


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜