Let's get this straight: you cannot sort NSDictionary.
Dictionary is a collection of keys and their objects without an order, therefore you cannot change that non-existing order. You can sort only array data types, since they are basically ordered lists.
There are still good news. You can get all keys from any dictionary as an array and sort them. Usually this is enough.
Showing posts with label compare. Show all posts
Showing posts with label compare. Show all posts
Thursday, December 8, 2011
How to Sort NSDictionary
Thursday, May 20, 2010
How to sort NSMutableArray alphabetically
NSMutableArray contains dynamic info objects, which are removed and added by user. Removal is easy, but addition should be done in alphabetical order.
What are your priorities: writing YASAIIRL algorithms or other features?
NSInteger myCompare(id item1, id item2, void *context)
{
return [(NSString *)((MyItem *)item1).title
localizedCaseInsensitiveCompare:
(NSString *)((MyItem *)item1).title];
}
- (void)addItem:(MyItem *)aItem
{
[self.myList addObject:aItem];
NSArray *temp = [NSArray arrayWithArray:self.myList];
self.myList = [NSMutableArray arrayWithArray:
[temp sortedArrayUsingFunction:myCompare context:NULL]];
}
Might be more fun to write your own Yet Another Search And Insert In Right Location algorithm, but this was fast to code, safe implementation and guaranteed to work.What are your priorities: writing YASAIIRL algorithms or other features?
Labels:
arrayWithArray,
compare,
iphone,
NSArray,
NSMutableArray,
NSString,
sort
Subscribe to:
Posts (Atom)