0

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

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?

  • 3
    there is no order in dictionary ... you need array of tuples – Bhavin Bhadani Apr 27 '16 at 07:21
  • Can you please explain it with reference to my code? thank you –  Apr 27 '16 at 07:22
  • 2
    Possible duplicate of [NSDictionary with ordered keys](http://stackoverflow.com/questions/376090/nsdictionary-with-ordered-keys) – Kurt Revis Apr 27 '16 at 07:22
  • NSDictionary stores its keys in a hash table, which is unordered by design. This lack of order is fundamental to the hash table storeage so yup. – NSNoob Apr 27 '16 at 07:22

3 Answers3

1

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.

1

NSDictionary is an unordered collection. To say "the order I added them" has no meaning. If you want to access the keys in a certain order then you'll either have to store an array along side your dictionary or get the keys and then sort them and use that to access the values in that order.

balkaran singh
  • 2,754
  • 1
  • 17
  • 32
0

There is no order in NSMutableDictionary If you want to use it you may use it by storing keys into an NSArray then iterate it and fetch its relevant values you want to use. Hope it works for you :)