如何在iOS中按修改日期对文件进行排序

use*_*015 6 iphone ipad ios

我使用NSFileManager来检索文件夹中的文件,我想按修改日期对它们进行排序.怎么做 ?

谢谢.

Cal*_*leb 9

你都尝试了些什么?

我没有这样做,但快速查看文档让我觉得你应该尝试以下方法:

  1. 调用-contentsOfDirectoryAtURL:includingPropertiesForKeys:options:error:并指定NSURLContentModificationDateKey为其中一个键.
  2. 您将获得一个NSURL对象数组,然后您可以使用NSArray方法对其进行排序-sortedArrayUsingComparator:.
  3. 传入比较器块,使用查找每个NSURL的修改日期-getResourceValue:forKey:error:.

更新:当我写上面的答案时,-getResourceValue:forKey:error:存在于iOS但没有做任何事情.该方法现在从iOS 5开始起作用.以下代码将记录应用程序的资源文件,后跟相应的修改日期列表:

NSFileManager *manager = [NSFileManager defaultManager];
NSArray *files = [manager contentsOfDirectoryAtURL:[[NSBundle mainBundle] resourceURL]
                        includingPropertiesForKeys:[NSArray arrayWithObject:NSURLContentModificationDateKey]
                                           options:nil
                                             error:nil];
NSMutableArray *dates = [NSMutableArray array];
for (NSURL *f in files) {
    NSDate *d = nil;
    if ([f getResourceValue:&d forKey:NSURLContentModificationDateKey error:nil]) {
        [dates addObject:d];
    }
}
NSLog(@"Files: %@", files);
NSLog(@"Dates: %@", dates);
Run Code Online (Sandbox Code Playgroud)