Having a little issue with NSDictionary and sorting. I’ve read a few posts on here about using certain methods such as sortedArrayUsingSelector and keysSortedByValueUsingComparator but cannot quite grasp it. At the moment I have a Table View Controller displaying some data correctly. The only issue I have is the order it is displaying it (or rather, the order of the sections).
In the declaration file:
@interface SettingsTableViewController : UITableViewController {
NSDictionary *tableContents;
NSArray *keys;
}
@property (nonatomic,retain) NSDictionary *data;
@property (nonatomic,retain) NSArray *keys;
@end
And the implementation file, for viewDidLoad:
NSArray *arrayTemporary1 = [[NSArray alloc]initWithObjects:@"Settings 1",@"Setting 2",@"Setting 3",@"Setting 4",nil];
NSArray *arrayTemporary2 = [[NSArray alloc]initWithObjects:@"Enable Gestures",nil];
NSArray *arrayTemporary3 = [[NSArray alloc]initWithObjects:@"Instructions",@"Frequently Asked Questions",@"About",nil];
NSDictionary *temporary =[[NSDictionary alloc]initWithObjectsAndKeys:arrayTemporary1,@"Settings",arrayTemporary2,@"Application",arrayTemporary3,@"Information",nil];
self.tableContents = temporary;
self.keys = [self.tableContents allKeys];
[temporary release];
[arrayTemporary1 release];
[arrayTemporary2 release];
[arrayTemporary3 release];
Individual cell data is accessed from an array NSArray *listData =[self.tableContents objectForKey:[self.keys objectAtIndex:[indexPath section]]]; inside the cellForRowAtIndexPath method.
Whilst this works fine, the issue I’m having is that rather than displaying the sections in the order that it is written in temporary, it does so randomly. Would appreciate some guidance.
Dictionaries do not guarantee ordering, so
tableContentshas no memory of the order in which you added the arrays to it. You should keep ordered data in NSArrays.Put the titles of the sections in a separate NSArray. Then use the dictionary you have to look up the data for the cells when you need to. This lets you keep the titles in the order you want, and still have a way to find the values in the dictionary.