简体   繁体   English

在NSArray中突变NSDictionary

[英]Mutating NSDictionary inside NSArray

Is there any quick way of mutating a NSArray of NSDictionaries? 有什么快速的方法可以使NSDictionaries的NSArray发生变异? I have a big NSArray and I want to update the value for a particular key inside the NSDictionary. 我有一个很大的NSArray,我想更新NSDictionary中特定键的值。 Is there any quick way of mutating the inner dictionaries so that I could update them. 有什么快速的方法可以更改内部字典,以便我可以对其进行更新。

I guess you want to modify all of the dictionaries simultaneously. 我猜您想同时修改所有词典。 Your dictionaries need to be NSMutableDictionary instances if you want to modify them. 如果要修改字典,则字典必须是NSMutableDictionary实例。

Assuming they are, you can modify all of them simultaneously using setValue:forKey: . 假设它们是,您可以使用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;
}

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 . 现在,在newArray上完成所有工作。

The below code will change a particular dictionary and return your NSArray instance. 以下代码将更改特定的字典并返回您的NSArray实例。
For below example arrayOfDictionaries is original array which contains all objects. 对于下面的示例, arrayOfDictionaries是包含所有对象的原始数组。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM