膜龈手术效果:DevDiv -- iOS 使用定制的NSDictionary的方法,对NSArray进行排序

来源:百度文库 编辑:中财网 时间:2024/04/29 05:01:14

使用定制的NSDictionary的方法,对NSArray进行排序

 

NSArray中存放的是NSDictionary,可以使用策略的方法对NSDictionary进行定制,增加比较的方法。然后调用NSArray的sortUsingSelector方法对数组进行排序,这里使用NSDictionay中的时间对象的时间排序。具体操作如下:

1.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

 

1.2        使用myCompareMethodWithDict对NSArray进行排序,假设NSArray是从plist文件中读取的NSDictionary对象的数组。

NSString* documentsDirectory = [pathsobjectAtIndex:0];

NSString *plistPath = [NSStringstringWithFormat:@"%@/XXX.plist",documentsDirectory];

NSMutableDictionary * cacheData = [[NSMutableDictionaryalloc] initWithContentsOfFile:plistPath];

[cacheArraysortUsingSelector:@selector(myCompareMethodWithDict:)];//根据时间降序排序

这样,cacheArray就是排序好的数组了。

 

 

 ? 2007-2011 DevDiv移动开发社区 http://www.devdiv.com