I have an array of NSString
values called sortedRefs
and each of them is also a key to a NSDictionary
called quotes
.
What I 'm trying to do is pass that key into a new NSDictionary
with its related value if a condition is met.
for (NSString *key in sortedRefs) {
NSLog(@"%@", key);
if ([[self.quotesManager.quotes[key] valueForKey:@"active"] boolValue]) {
[self.activeQuotes setObject:self.quotesManager.quotes[key] forKey:key];
NSLog(@"%@", [self.activeQuotes allKeys]);
}
}
The problem is that the activeQuotes
dictionary is not populated in the order I insert values in. To be more specific my output after the first three loops is
2016-05-26 23:10:59.939 Project[2553:94502] DE2109D0C637CBD755E91ED18F85C17E
2016-05-26 23:10:59.940 Project[2553:94502] (
DE2109D0C637CBD755E91ED18F85C17E
)
2016-05-26 23:10:59.940 Project[2553:94502] 309FFEB2DEC0F938D3E5FFD39112F9F6
2016-05-26 23:10:59.940 Project[2553:94502] (
DE2109D0C637CBD755E91ED18F85C17E,
309FFEB2DEC0F938D3E5FFD39112F9F6
)
2016-05-26 23:10:59.940 Project[2553:94502] 925DEC6CFB3FDF87530677FE93E97A46
2016-05-26 23:10:59.940 Project[2553:94502] (
925DEC6CFB3FDF87530677FE93E97A46,
DE2109D0C637CBD755E91ED18F85C17E,
309FFEB2DEC0F938D3E5FFD39112F9F6
)
As you can see when I insert 925DEC6CFB3FDF87530677FE93E97A46
instead of going after the 309FFEB2DEC0F938D3E5FFD39112F9F6
key it goes on top. As the loops go on this happens more frequently and I end up with a completely different order than the one I had in the sortedRefs
array.
Is there a way to keep the order while inserting new entries in my dictionary?
Dictionaries are not stored in any guaranteed order. They are designed to be referenced by key. If you want to access them in a particular order, you need to keep an ordered collection of the keys (e.g. array) and use that to choose them.