Saturday, November 20, 2010

Sorting NSMutableArray of NSDictionary

NSString * NAME = @"name";
NSString * ADDRESS = @"address";
NSString * FREQUENCY = @"frequency";
NSString * TYPE = @"type";

NSMutableArray * array = [NSMutableArray array];

NSDictionary * dict;

dict = [NSDictionary dictionaryWithObjectsAndKeys:
@"Alehandro", NAME, @"Sydney", ADDRESS,
[NSNumber numberWithInt:100], FREQUENCY,
@"T", TYPE, nil];
[array addObject:dict];

dict = [NSDictionary dictionaryWithObjectsAndKeys:
@"Xentro", NAME, @"Melbourne", ADDRESS,
[NSNumber numberWithInt:50], FREQUENCY,
@"X", TYPE, nil];
[array addObject:dict];

dict = [NSDictionary dictionaryWithObjectsAndKeys:
@"John", NAME, @"Perth", ADDRESS,
[NSNumber numberWithInt:75],
FREQUENCY, @"A", TYPE, nil];
[array addObject:dict];

dict = [NSDictionary dictionaryWithObjectsAndKeys:
@"Fjord", NAME, @"Brisbane", ADDRESS,
[NSNumber numberWithInt:20], FREQUENCY,
@"B", TYPE, nil];
[array addObject:dict];


Sorting part using descriptors with the Frequency field which is NSNumber:

NSSortDescriptor * frequencyDescriptor =
[[[NSSortDescriptor alloc] initWithKey:FREQUENCY
ascending:YES] autorelease];

id obj;
NSEnumerator * enumerator = [array objectEnumerator];
while ((obj = [enumerator nextObject])) NSLog(@"%@", obj);

NSArray * descriptors =
[NSArray arrayWithObjects:frequencyDescriptor, nil];
NSArray * sortedArray =
[array sortedArrayUsingDescriptors:descriptors];

NSLog(@"\nSorted Array ..");

enumerator = [sortedArray objectEnumerator];
while ((obj = [enumerator nextObject])) NSLog(@"%@", obj);


OUTPUT - sorted by Frequency field
2009-12-04 x[1] {address = Sydney; frequency = 100; name = Alehandro; type = T; }
x[1] {address = Melbourne; frequency = 50; name = Xentro; type = X; }
x[1] {address = Perth; frequency = 75; name = John; type = A; }
x[1] {address = Brisbane; frequency = 20; name = Fjord; type = B; }
Sorted Array ..
x[1] {address = Brisbane; frequency = 20; name = Fjord; type = B; }
x[1] {address = Melbourne; frequency = 50; name = Xentro; type = X; }
x[1] {address = Perth; frequency = 75; name = John; type = A; }
x[1] {address = Sydney; frequency = 100; name = Alehandro; type = T; }