[ACCEPTED]-NSDictionary with ordered keys-nsdictionary
The solution of having an associated NSMutableArray 4 of keys isn't so bad. It avoids subclassing 3 NSDictionary, and if you are careful with 2 writing accessors, it shouldn't be too hard 1 to keep synchronised.
I'm late to the game with an actual answer, but 8 you might be interested to investigate CHOrderedDictionary. It's 7 a subclass of NSMutableDictionary which 6 encapsulates another structure for maintaining 5 key ordering. (It's part of CHDataStructures.framework.) I find it 4 to be more convenient than managing a dictionary 3 and array separately.
Disclosure: This is 2 open-source code which I wrote. Just hoping 1 it may be useful to others facing this problem.
There is no such inbuilt method from which 8 you can acquire this. But a simple logic 7 work for you. You can simply add few numeric 6 text in front of each key while you prepare 5 the dictionary. Like
NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:
@"01.Created",@"cre",
@"02.Being Assigned",@"bea",
@"03.Rejected",@"rej",
@"04.Assigned",@"ass",
@"05.Scheduled",@"sch",
@"06.En Route",@"inr",
@"07.On Job Site",@"ojs",
@"08.In Progress",@"inp",
@"09.On Hold",@"onh",
@"10.Completed",@"com",
@"11.Closed",@"clo",
@"12.Cancelled", @"can",
nil];
Now if you can use sortingArrayUsingSelector 4 while getting all keys in the same order 3 as you place.
NSArray *arr = [[dict allKeys] sortedArrayUsingSelector:@selector(localizedStandardCompare:)];
At the place where you want 2 to display keys in UIView, just chop off 1 the front 3 character.
If you're going to subclass NSDictionary 12 you need to implement these methods as a 11 minimum:
- NSDictionary
-count
-objectForKey:
-keyEnumerator
- NSMutableDictionary
-removeObjectForKey:
-setObject:forKey:
- NSCopying/NSMutableCopying
-copyWithZone:
-mutableCopyWithZone:
- NSCoding
-encodeWithCoder:
-initWithCoder:
- NSFastEnumeration (for Leopard)
-countByEnumeratingWithState:objects:count:
The easiest way to do what you want 10 is to make a subclass of NSMutableDictionary 9 that contains its' own NSMutableDictionary 8 that it manipulates and an NSMutableArray 7 to store an ordered set of keys.
If you're 6 never going to encode your objects you could 5 conceivable skip implementing -encodeWithCoder:
and -initWithCoder:
All of 4 your method implementations in the 10 methods 3 above would then either go directly through 2 your hosted dictionary or your ordered key 1 array.
My little addition: sorting by numeric key 1 (Using shorthand notations for smaller code)
// the resorted result array
NSMutableArray *result = [NSMutableArray new];
// the source dictionary - keys may be Ux timestamps (as integer, wrapped in NSNumber)
NSDictionary *dict =
@{
@0: @"a",
@3: @"d",
@1: @"b",
@2: @"c"
};
{// do the sorting to result
NSArray *arr = [[dict allKeys] sortedArrayUsingSelector:@selector(compare:)];
for (NSNumber *n in arr)
[result addObject:dict[n]];
}
Quick 'n dirty:
When you need to order your 7 dictionary (herein called “myDict”), do 6 this:
NSArray *ordering = [NSArray arrayWithObjects: @"Thing",@"OtherThing",@"Last Thing",nil];
Then, when you need to order your dictionary, create 5 an index:
NSEnumerator *sectEnum = [ordering objectEnumerator];
NSMutableArray *index = [[NSMutableArray alloc] init];
id sKey;
while((sKey = [sectEnum nextObject])) {
if ([myDict objectForKey:sKey] != nil ) {
[index addObject:sKey];
}
}
Now, the *index object will contain 4 the appropriate keys in the correct order. Note 3 that this solution does not require that 2 all the keys necessarily exist, which is 1 the usual situation we're dealing with...
Minimal implementation of an ordered subclass 2 of NSDictionary (based on https://github.com/nicklockwood/OrderedDictionary). Feel free to 1 extend for your needs:
Swift 3 and 4
class MutableOrderedDictionary: NSDictionary {
let _values: NSMutableArray = []
let _keys: NSMutableOrderedSet = []
override var count: Int {
return _keys.count
}
override func keyEnumerator() -> NSEnumerator {
return _keys.objectEnumerator()
}
override func object(forKey aKey: Any) -> Any? {
let index = _keys.index(of: aKey)
if index != NSNotFound {
return _values[index]
}
return nil
}
func setObject(_ anObject: Any, forKey aKey: String) {
let index = _keys.index(of: aKey)
if index != NSNotFound {
_values[index] = anObject
} else {
_keys.add(aKey)
_values.add(anObject)
}
}
}
usage
let normalDic = ["hello": "world", "foo": "bar"]
// initializing empty ordered dictionary
let orderedDic = MutableOrderedDictionary()
// copying normalDic in orderedDic after a sort
normalDic.sorted { $0.0.compare($1.0) == .orderedAscending }
.forEach { orderedDic.setObject($0.value, forKey: $0.key) }
// from now, looping on orderedDic will be done in the alphabetical order of the keys
orderedDic.forEach { print($0) }
Objective-C
@interface MutableOrderedDictionary<__covariant KeyType, __covariant ObjectType> : NSDictionary<KeyType, ObjectType>
@end
@implementation MutableOrderedDictionary
{
@protected
NSMutableArray *_values;
NSMutableOrderedSet *_keys;
}
- (instancetype)init
{
if ((self = [super init]))
{
_values = NSMutableArray.new;
_keys = NSMutableOrderedSet.new;
}
return self;
}
- (NSUInteger)count
{
return _keys.count;
}
- (NSEnumerator *)keyEnumerator
{
return _keys.objectEnumerator;
}
- (id)objectForKey:(id)key
{
NSUInteger index = [_keys indexOfObject:key];
if (index != NSNotFound)
{
return _values[index];
}
return nil;
}
- (void)setObject:(id)object forKey:(id)key
{
NSUInteger index = [_keys indexOfObject:key];
if (index != NSNotFound)
{
_values[index] = object;
}
else
{
[_keys addObject:key];
[_values addObject:object];
}
}
@end
usage
NSDictionary *normalDic = @{@"hello": @"world", @"foo": @"bar"};
// initializing empty ordered dictionary
MutableOrderedDictionary *orderedDic = MutableOrderedDictionary.new;
// copying normalDic in orderedDic after a sort
for (id key in [normalDic.allKeys sortedArrayUsingSelector:@selector(compare:)]) {
[orderedDic setObject:normalDic[key] forKey:key];
}
// from now, looping on orderedDic will be done in the alphabetical order of the keys
for (id key in orderedDic) {
NSLog(@"%@:%@", key, orderedDic[key]);
}
For, Swift 3. Please try out the following approach
//Sample Dictionary
let dict: [String: String] = ["01.One": "One",
"02.Two": "Two",
"03.Three": "Three",
"04.Four": "Four",
"05.Five": "Five",
"06.Six": "Six",
"07.Seven": "Seven",
"08.Eight": "Eight",
"09.Nine": "Nine",
"10.Ten": "Ten"
]
//Print the all keys of dictionary
print(dict.keys)
//Sort the dictionary keys array in ascending order
let sortedKeys = dict.keys.sorted { $0.localizedCaseInsensitiveCompare($1) == ComparisonResult.orderedAscending }
//Print the ordered dictionary keys
print(sortedKeys)
//Get the first ordered key
var firstSortedKeyOfDictionary = sortedKeys[0]
// Get range of all characters past the first 3.
let c = firstSortedKeyOfDictionary.characters
let range = c.index(c.startIndex, offsetBy: 3)..<c.endIndex
// Get the dictionary key by removing first 3 chars
let firstKey = firstSortedKeyOfDictionary[range]
//Print the first key
print(firstKey)
0
I don’t like C++ very much, but one solution 14 that I see myself using more and more is 13 to use Objective-C++ and std::map
from the Standard 12 Template Library. It is a dictionary whose 11 keys are automatically sorted on insertion. It 10 works surprisingly well with either scalar 9 types or Objective-C objects both as keys 8 and as values.
If you need to include an 7 array as a value, just use std::vector
instead of NSArray
.
One 6 caveat is that you might want to provide 5 your own insert_or_assign
function, unless you can use C++17 4 (see this answer). Also, you need to typedef
your types to 3 prevent certain build errors. Once you figure 2 out how to use std::map
, iterators etc., it is pretty 1 straightforward and fast.
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.