NSDictionary with ordered keys
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
Introduction
NSDictionary in Objective-C (and Dictionary in Swift) does not guarantee key order. If you need ordered keys, use a separate NSArray to track key order alongside the dictionary, use NSOrderedSet for unique ordered keys, or create a custom ordered dictionary wrapper. In Swift, third-party libraries like OrderedDictionary from the Swift Collections package provide this functionality directly.
NSDictionary Is Unordered
Solution 1: Separate Key Array
The simplest approach — maintain an array of keys in the desired order:
For mutable dictionaries:
Solution 2: Custom Ordered Dictionary Class
Usage:
Solution 3: Sorted Keys
If you want alphabetical order (not insertion order):
Swift: OrderedDictionary (Swift Collections)
Swift: Manual Approach
Common Pitfalls
- Assuming NSDictionary preserves insertion order:
NSDictionaryand SwiftDictionarydo not guarantee any key ordering. Even if keys appear ordered in small tests, the order can change with different data sizes or runtime conditions. - Using
allKeysand expecting consistent order:[dict allKeys]returns keys in an arbitrary order that may differ between calls (though it is typically stable within a single run). Never rely on it for ordered iteration. - Not keeping the key array in sync: When using a separate
NSMutableArrayfor ordered keys, forgetting to add/remove keys when modifying the dictionary causes inconsistencies. Always wrap both operations in a helper method. - Performance of linear search in key array:
[NSMutableArray removeObject:]andcontainsObject:are O(n). For large dictionaries (1000+ keys), this becomes slow. UseNSMutableOrderedSetinstead ofNSMutableArrayfor O(1) lookups. - JSON serialization losing order:
NSDictionaryserialized to JSON viaNSJSONSerializationdoes not preserve key order. If key order matters for the JSON output, serialize manually or use an ordered JSON library.
Summary
NSDictionaryand SwiftDictionaryare unordered — key iteration order is not guaranteed- Maintain a separate
NSArray/Arrayof keys alongside the dictionary for insertion order - Use the Swift Collections package (
OrderedDictionary) for a production-ready ordered dictionary - Sort keys with
sortedArrayUsingSelector:orsorted()for alphabetical order - Wrap key array + dictionary operations in a custom class to keep them synchronized
- For JSON output with ordered keys, use a specialized serialization approach
Related reading
- nservicebus send command object with list type property using msmq transport
- Number of assignments necessary to find the minimum value in an array?
- Number of binary search trees over n distinct elements
- Numpy - add row to array
- NSIndexpath.item vs NSIndexpath.row
- NSInvalidUnarchiveOperationException Could not instantiate class named NSLayoutConstraint
- Numpy array dimensions
- NumPy array initialization fill with identical values

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.