订购带有日期的NSMutableArray

时间:2014-06-15 20:46:58

标签: ios objective-c nsmutablearray nsdate

我有一个NSMutableArray文件名,我可以访问这些文件修改日期:

NSMutableDictionary* dict = [[NSMutableDictionary alloc]init];
for (NSString* str in documentsArray) {
    NSString* str2 = [DKStoreManager dateFileWasModifiedWithFileName:str inFolderNumber:folderNumber forUser:userID andType:type];
    [dict setObject:str2 forKey:str];
}
NSArray * dateArray = [dict allValues];
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"self" ascending:NO];
NSArray *descriptors = [NSArray arrayWithObject: descriptor];

NSArray *reverseOrder = [dateArray sortedArrayUsingDescriptors:descriptors];

NSMutableArray* arr2 = [[NSMutableArray alloc]init];
for (NSString * date in reverseOrder){
    NSArray *temp = [dict allKeysForObject:date];

    NSString * your_value = [dict valueForKey:[temp lastObject]];
    [arr2 addObject:your_value];
}
return arr2;

documentsArray只是一个文件名列表,如下所示:

"ale and  1.png",
"yyyy 1.png",
"the fact that  1.png",

我正在尝试将名称与相应日期放在字典中,然后命令字典日期,我设置了对象,最后返回文件名的红色列表。如果我使用文件名作为对象而日期作为键,则某些日期相同,因此它们只被接受一次。另一方面,如果我用日期作为对象,那么我就无法回到钥匙......

1 个答案:

答案 0 :(得分:1)

我建议您创建自己的模型对象并使用它而不是使用NSDictionary。例如:

@interface Model : NSObject

@property (nonatomic, strong) NSDate *someDate;
@property (nonatomic, copy) NSString *someString;


- (instancetype)initWithString:(NSString *)string date:(NSDate *)date;

@end

@implementation Model


- (instancetype)initWithString:(NSString *)string date:(NSDate *)date
{
    self = [super init];
    if (self) {
        _someString = [string copy];
        _someDate = date;
    }
    return self;
}

@end

然后,如果您拥有这些NSArray Models,您可以使用KVC获取特定密钥的数组并执行您需要的任何操作,例如:

Model *model1 = [[Model alloc] initWithString:@"Model 1"
                                         date:[NSDate dateWithTimeIntervalSinceNow:10]];
Model *model2 = [[Model alloc] initWithString:@"Model 2"
                                         date:[NSDate dateWithTimeIntervalSinceNow:20]];
NSArray *array = @[model1, model2];

NSLog(@"stringArray:%@", [array valueForKey:@"someString"]);
NSLog(@"dateArray:%@", [array valueForKey:@"someDate"]);