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

本文介绍如何在Swift中通过策略方法定制和排序NSDictionary,包括实现自定义比较方法及应用到NSArray排序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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就是排序好的数组了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值