首先,给NSMutableDictionary建一个分类,里面加上自定义的排序方法。
头文件:
#import <Foundation/Foundation.h> @interface NSMutableDictionary(NSMutableDictionaryCompare) - (NSComparisonResult)compareWithDictionary:(NSMutableDictionary *) dic; @end
实现文件:
#import "CustomCompare.h" @implementation NSMutableDictionary(NSMutableDictionaryCompare) - (NSComparisonResult)compareWithDictionary:(NSMutableDictionary *) dic{ NSMutableDictionary *dic1 = self; NSString *name1 = [dic1 objectForKey:@"Name"]; NSString *name2 = [dic objectForKey:@"Name"]; return [name2 compare:name1]; } @end
示例:
NSMutableDictionary *dic1 = [[NSMutableDictionary alloc] initWithObjectsAndKeys:@"Michael", @"Name", @"26", @"Age", nil]; NSMutableDictionary *dic2 = [[NSMutableDictionary alloc] initWithObjectsAndKeys:@"Eric", @"Name", @"24", @"Age", nil]; NSMutableDictionary *dic3 = [[NSMutableDictionary alloc] initWithObjectsAndKeys:@"Emilla", @"Name", @"25", @"Age", nil]; NSMutableDictionary *dic4 = [[NSMutableDictionary alloc] initWithObjectsAndKeys:@"Josh", @"Name", @"32", @"Age", nil]; NSMutableDictionary *dic5 = [[NSMutableDictionary alloc] initWithObjectsAndKeys:@"Echo", @"Name", @"22", @"Age", nil]; NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:dic1, dic2, dic3, dic4, dic5, nil]; [dic1 release]; [dic2 release]; [dic3 release]; [dic4 release]; [dic5 release]; [array sortUsingSelector:@selector(compareWithDictionary:)]; NSLog(@"%@", array); [array release];
示例输出:
{ Age = 26; Name = Michael; }, { Age = 32; Name = Josh; }, { Age = 24; Name = Eric; }, { Age = 25; Name = Emilla; }, { Age = 22; Name = Echo; }