迭代NSDictionary时保持顺序 [英] Maintaining the order while iterating a NSDictionary
问题描述
我有一个NSDictionary,它可以如下迭代和将数据保存到核心数据中,
I have a NSDictionary which im iterating and Im saving the datas to core data as follows,
NSDictionary *details = [valueDict objectForKey:@"shipment_master"];
for (NSDictionary *response in details) {
NSManagedObjectContext *context = [self managedObjectContext];
// remove all rows
[context performBlockAndWait:^{
// add new row(s)
NSManagedObject *master = [NSEntityDescription insertNewObjectForEntityForName:@"ShipmentMaster" inManagedObjectContext:context];
NSError *error;
[master setValue:[details objectForKey:response] forKey:@"values"];
// save MOC
if ([context hasChanges]) {
(void)[context save:&error];
}
}];
}
问题在于循环nsdictionary时顺序正在更改.例如,字典中a紧接b之后是c,d等,但是当我对其进行迭代并保存时,顺序正在更改,该如何维护顺序?
The problem is that the order is being changed while looping the nsdictionary. For instance a comes after b then c ,d etc in the dictionary but when Im iterating it and saving it, the order is being changed, How can I maintain the order?
推荐答案
NSMutableDictionary
不排序.您无法做任何保证键顺序的操作,因为NSDictionary
不会尝试保留任何特定的顺序.要按特定顺序浏览字典,必须按所需顺序对键进行NSArray
的操作,然后对其进行迭代并获取相应的值.
NSMutableDictionary
is not ordered. There is nothing you can do to guarantee the order of keys because NSDictionary
makes no attempt to preserve any particular ordering. To go over a dictionary in a particular order, you have to make an NSArray
of the keys that is in the order you want, then iterate that and fetch the corresponding values.
这篇关于迭代NSDictionary时保持顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!