NSDictionary order changes allKeys and allValues
I have a view controller that has a table view on it and for this table view data source I am using NSDictionary
which contains two keys and two values. I am initializing a dictionary with an object literal, and I also have NSArray
one that contains the values ββthat should match the values ββin the dictionary.
NSDictionary *dict = @{@"Key1" : @"Value1", @"Key2" : @"Value2"};
NSArray *arr = @[@"Value for Key 1", @"Value for Key 2"];
In my table view cellForRowAtIndexPath:
, I have the following
static NSString *cellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (!cell)
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
cell.textLabel.text = dict.allKeys[indexPath.row];
cell.imageView.image = dict.allValues[indexPath.row];
cell.textLabel.numberOfLines = 0;
return cell;
However, no matter the order in which I initialize dict
(it might be @{@"Key2" : @"Value2", @"Key1" : @"Value1"}
), the value 2 will always be the first. This causes problems when adding more objects to the dictionary, since the indices in arr
must be the same as the indices in dict
and this problem also causes the table view to be different from what I want, Does anyone know what is going wrong here?
To visualize the problem, here is a diagram to demonstrate
NSDictionary *dict = @{@"Key1" : @"Value1", @"Key2" : @"Value2"};
----------------------------------------
Table view
----------------------------------------
[Value 2] [Key 2]
----------------------------------------
[Value 1] [Key 1]
----------------------------------------
//if I change the order in the dictionary, the order in the table view remains the same
NSDictionary *dict = @{@"Key2" : @"Value2", @"Key1" : @"Value1"};
----------------------------------------
Table view
----------------------------------------
[Value 2] [Key 2]
----------------------------------------
[Value 1] [Key 1]
----------------------------------------
source to share
Nothing bad happens here. NSDictionary is an unordered collection. It doesn't make sense to say "the order I added".
If you want to access the keys in a specific order, you will either have to store the array next to your dictionary, or get the keys and then sort them and use them to access the values ββin that order.
source to share