使用定制的NSDictionary的方法,对NSArray进行排序(附:数组排序两种常见方法)
NSArray中存放的是NSDictionary,可以使用策略的方法对NSDictionary进行定制,增加比较的方法。然后调用NSArray的sortUsingSelector方法对数组进行排序,这里使用NSDictionay中的时间对象的时间排序。具体操作如下:
1.定制NSDictionary
XXX.h文件
@interface NSMutableDictionary(myCompare)
-(NSComparisonResult)myCompareMethodWithDict: (NSMutableDictionary*)theOtherDict;
@end
XXX.m文件
#import "CustomDictionary.h"
@implementation NSMutableDictionary(myCompare)
- (NSComparisonResult)myCompareMethodWithDict:(NSMutableDictionary*)anotherDict
{
NSMutableDictionary *firstDict = self;
NSDate *firstDate = [firstDict objectForKey: @"browseTime"];
NSDate *secondDate = [anotherDict objectForKey: @"browseTime"];
//return [firstDate compare: secondDate];
return [secondDate compare: firstDate];
}
@end
2.使用myCompareMethodWithDict对NSArray进行排序,假设NSArray是从plist文件中读取的NSDictionary对象的数组。
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *plistPath = [NSString stringWithFormat:@"%@/XXX.plist",documentsDirectory];
NSMutableDictionary * cacheData = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
[cacheArray sortUsingSelector:@selector(myCompareMethodWithDict:)];//根据时间降序排序
这样,cacheArray就是排序好的数组了。
数组排序两种常见方法:
1.
[myArray.name sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
2.
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES selector:@selector(caseInsensitiveCompare:)];
NSArray* sortedArray =[myArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];