pithhelmet
pithhelmet

Reputation: 2272

Sort a NSMutuableArray

I have a NSMutableArray that is loaded with a inforamtion from a dictionary...

[self.data removeAllObjects];  
NSMutableDictionary *rows = [[NSMutableDictionary alloc] initWithDictionary:[acacheDB.myDataset getRowsForTable:@"sites"]];      
self.data = [[NSMutableArray alloc] initWithArray:[rows allValues]];      

There are two key value pairs in the rows dictionary.

I need to sort the self.data NSMutableArray in alphabetical order.

How is this accomplished??

thanks
tony

Upvotes: 2

Views: 5117

Answers (2)

Regexident
Regexident

Reputation: 29552

This should do:

[self.data removeAllObjects];
NSArray *values = [[acacheDB.myDataset getRowsForTable:@"sites"] allValues];
NSSortDescriptor *alphaDescriptor = [[NSSortDescriptor alloc] initWithKey:@"DCFProgramName" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)];
NSArray *sortedValues = [values sortedArrayUsingDescriptors:[NSMutableArray arrayWithObjects:alphaDescriptor, nil]];
[alphaDesc release];
[self.data addObjectsFromArray:sortedValues];
  1. There's no need to clear an NSMutableArray if you're replacing it shortly afterwards.
  2. There's no need to create an additional NSMutableDictionary, if you're not modifying anything in it.
  3. There's no need to create an additional NSMutableArray, if you could just as well just add the values to the existing one.

Also: There are some serious memory leaks in your code. (2x alloc + 0x release = 2x leak)

Edit: updated code snippet to reflect OP's update on data structure.

Upvotes: 0

ynnckcmprnl
ynnckcmprnl

Reputation: 4352

If the values are plain strings you can use the following to create a sorted array:

NSArray *sorted = [values sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];

Upvotes: 4

Related Questions