Search code examples
iosobjective-cobject-literal

NSDictionary literals position at run-time


How can I ensure the position of key-value pairs inside a NSDictionary when defining it?

For example if I define:

[detailsView setDatasource: @[ 
   @[@"Details",
      @{ @"title_1":@"description1",
         @"title_2":@"description2",
         @"title_3":@"description3",
         @"title_4":@"description4" }],
   @[@"Actions",
      @{ @"Action_1":[NSNull null],
         @"Action_2":[NSNull null],
         @"Action_3":[NSNumber numberWithBool:false] }]
];

Then at runtime I have different order of items

[detailsView setDatasource: @[ 
   @[@"Details",
      @{ @"title_2":@"description2",
         @"title_3":@"description3",
         @"title_4":@"description4",
         @"title_1":@"description1" }],
   @[@"Actions",
      @{ @"Action_3":[NSNumber numberWithBool:false],
         @"Action_1":[NSNull null],
         @"Action_2":[NSNull null]}]
];

This behaviour is unpredictable... How NSDictionary is initialised when initialising it with literals , and is there a way of ensure that a key-value pair will be at defined position when using literals ?

-- EDIT --

Not a brilliant solution but works. I ended-up doing like this:

@[
    @[ @"Route details",
         @[
              @[@"route-direction", @"Route direction", [NSString stringWithFormat:@"%@ → %@", journey[@"from"], journey[@"to"]]],
              @[@"poi-count", @"Points of interest", journey[@"pois-count"]],
              @[@"date-created", @"Date created", journey[@"created-at"]],
          ]
     ],
    @[ @"Actions" ,
         @[
             @[@"favourite", @"Favourite", ( [journey objectForKey:@"favourite"] ? [journey objectForKey:@"favourite"] : [NSNumber numberWithBool:false])],
             @[@"load",@"Load now",[NSNull null]],
             @[@"delete",@"Delete",[NSNull null]],
          ]
     ],
[NSNumber numberWithInteger: indexPath.row]]];

Solution

  • NSDictionary is not a ordered container.If you use it,you should not care the order of data.

    If you want a ordered dictionary,refer to this link

    http://www.cocoawithlove.com/2008/12/ordereddictionary-subclassing-cocoa.html

    Or you may write another NSArray/NSMutableArray to keep the keys order of this NSDictionary.

    Or just use NSArray instead of NSDictionary,one array keep keys,another array keep values

    Hope this could be helpful