Translate

2012年9月25日 星期二

NSArray compare 排序

其實一般NSArray的排序

NSArray *sortedArray = [temp_dic_dic sortedArrayUsingSelector:@selector(compare:)]; for(int i =0; i < [sortedArray count]; i++) { int x = [[sortedArray objectAtIndex:i] intValue]; NSLog(@"x is %d",x); }

但是我需要的是針對NSArray多個dictionary,每個dictionary都有個key值為"dddNumber",key值的形態為字串,如何依照NSString比對呢?

NSMutableArray *array = [[NSMutableArray alloc] init]; for (int i = 0; i < 10; i ++) { NSDictionary *aDict = [[NSDictionary alloc] initWithObjectsAndKeys:[NSString stringWithFormat:@"akdj%i", i], @"phaseNumber", nil]; [array addObject:aDict]; [aDict release]; } // 排序 NSSortDescriptor *sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"dddNumber" ascending:YES] autorelease]; NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor]; NSArray *sortedArray = [array sortedArrayUsingDescriptors:sortDescriptors];
是要用intValue排序的话。上面代码是不对的,上面是按照String来排序的。 如果要按照intValue排序,参见如下:

方法
NSComparisonResult compare(NSDictionary *firstDict, NSDictionary *secondDict, void *context) {NSLog(@"IN(%i, %i)", [[firstDict objectForKey:@"ddd"] intValue], [[secondDict objectForKey:@"ddd"] intValue]); if ([[firstDict objectForKey:@"ddd"] intValue] < [[secondDict objectForKey:@"ddd"] intValue]) return NSOrderedAscending; else if ([[firstDict objectForKey:@"ddd"] intValue] > [[secondDict objectForKey:@"ddd"] intValue]) return NSOrderedDescending; else return NSOrderedSame; } [array sortUsingFunction:compare context:NULL];
使用
[array sortUsingFunction:compare context:NULL];

沒有留言:

張貼留言