迭代NSDictionary时保持顺序 [英] Maintaining the order while iterating a NSDictionary

查看:388
本文介绍了迭代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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆