Mutating NSDictionary inside NSArray

Is there any quick way of mutating a NSArray of NSDictionaries? I have a big NSArray and I want to update the value for a particular key inside the NSDictionary. Is there any quick way of mutating the inner dictionaries so that I could update them.

Answers


Assuming your original array contains immutable dictionaries then one way is to create a new array with mutable copies of all of the original dictionaries.

NSMutableArray *newArray = [NSMutableArray arrayWithCapacity:oldArray.count];
for (NSDictionary *dict in oldArray) {
    [newArray addObject:[dict mutableCopy]];
}

Now do all of your work on newArray.


I guess you want to modify all of the dictionaries simultaneously. Your dictionaries need to be NSMutableDictionary instances if you want to modify them.

Assuming they are, you can modify all of them simultaneously using setValue:forKey:. Example:

static NSMutableDictionary *dictionary() {
    return [@{ @"first": @"Oscar", @"second": @"Meyer" } mutableCopy];
}

int main(int argc, const char * argv[])
{
    @autoreleasepool {
        NSArray *array = @[ dictionary(), dictionary(), dictionary() ];
        [array setValue:@"Humphrey" forKey:@"first"];
        NSLog(@"%@", array);
    }
    return 0;
}

The below code will change a particular dictionary and return your NSArray instance. For below example arrayOfDictionaries is original array which contains all objects.

NSDictionary *dic1 = @{@"key":@"object1"};
NSDictionary *dic2 = @{@"key":@"object2"};
NSDictionary *dic3 = @{@"key":@"object3"};

NSArray *arrayOfDictionaries=@[dic1,dic2,dic3];
NSMutableArray *mutableArray =[NSMutableArray arrayWithArray:arrayOfDictionaries];

//suppose you want to modify dic2

NSInteger index=[arrayOfDictionaries indexOfObject:dic2];
//index will be 1

NSMutableDictionary *mutableDic =[NSMutableDictionary dictionaryWithDictionary:dic2];
[mutableDic setObject:@"objectChanged" forKey:@"key"];
NSDictionary *changedDic = [NSDictionary dictionaryWithDictionary:mutableDic];
[mutableArray replaceObjectAtIndex:index withObject:changedDic];

arrayOfDictionaries = [NSArray arrayWithArray:mutableArray];
NSLog(@"%@",arrayOfDictionaries[1]); 

LOGS

{
    key = objectChanged;
}

Need Your Help

Many-To-One, Self-referencing with Inheritance Mapping

symfony inheritance orm doctrine self-reference

I have some entites with common relations and attributes. So, I want to simplify my schema using inheritance mapping.

PDF XFA Form Read-Only with iTextSharp

c# pdf readonly xfa

I have finally, successfully, figured out how to fill a PDF with an XFA Form with my custom data using iTextSharp.