http://stackoverflow.com/questions/1844031/how-to-sort-nsmutablearray-using-sortedarrayusingdescriptors
Example using
Example using
NSString
and NSNumber
values with sorting on NSNumber
value: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 ..."); 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; }
2009-12-04 x[1] {address = Melbourne; frequency = 50; name = Xentro; type = X; } 2009-12-04 x[1] {address = Perth; frequency = 75; name = John; type = A; } 2009-12-04 x[1] {address = Brisbane; frequency = 20; name = Fjord; type = B; } 2009-12-04 x[1] Sorted ... 2009-12-04 x[1] {address = Brisbane; frequency = 20; name = Fjord; type = B; } 2009-12-04 x[1] {address = Melbourne; frequency = 50; name = Xentro; type = X; } 2009-12-04 x[1] {address = Perth; frequency = 75; name = John; type = A; } 2009-12-04 x[1] {address = Sydney; frequency = 100; name = Alehandro; type = T; }
Comments
Post a Comment