Reputation: 261
I am tring to populate a picker from a dictionary, and i have a dictionary
NSMutableArray* type1names = [NSMutableArray arrayWithObjects:@"--",@"AA",@"AB",@"BA",@"BB",@"BC",@"CB",@"CC",@"CD",@"DC",@"DD",@"FF",nil];
NSMutableArray* type1points = [NSMutableArray arrayWithObjects:@"-",@"4",@"3.7",@"3.3",@"3.0",@"2.7",@"2.3",@"2.0",@"1.7",@"1.3",@"1",@"0", nil];
NSMutableDictionary *type1 = [[NSMutableDictionary alloc] initWithObjects:type1points forKeys:type1names];
initialized like this. The problem occurs when i try to get them back as i put them into the Dictionary with the code below.
- (NSString *)pickerView:(UIPickerView *)thePickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
YOHAppDelegate *app = [UIApplication sharedApplication].delegate;
NSString *key = [[app.pointsDictionary allKeys] objectAtIndex:row];
return key;
}
They come back from dictionary unordered. Not random, always in same positions, but without any logical system.
Is there a way to implement this, or should i use multiple arrays for this?
Upvotes: 3
Views: 727
Reputation: 47699
An NSDictionary has no (externally defined/documented) order for its elements. If you want them ordered you need a different scheme.
Upvotes: 2
Reputation: 52227
A Hot Licks said, NSDictionary does not save the order. However Matt Gallagher shows how to create an OrderedDictionary by subclassing NSMutableDictionary.
On the other hand you should take his warning seriously. But the certain way, he subclasses it gives us a pattern, that can be used without subclassing: You can define a class, that holds an dictionary and an array, but inherits from NSObject. Define a setObjectForKey:
method, that forwards to NSDictionary and add the object to the array (just, if it wasn't present in the dictionary). Add an method objectForKey:
, that forwards to the dictionary and objectAtIndex:
that forwards to the array.
Upvotes: 3