如何在iOS中按修改日期对文件进行排序 [英] How to sort files by modified date in iOS

查看:903
本文介绍了如何在iOS中按修改日期对文件进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I used NSFileManager to retrieve the files in a folder, and I want to sort them by modified date. How to do that ?

谢谢。

推荐答案

你有什么到目前为止尝试了吗?

What have you tried so far?

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

I haven't done this, but a quick look at the docs makes me think that you should try the following:


  1. 调用 -contentsOfDirectoryAtURL:includingPropertiesForKeys:options:error:并指定 NSURLContentModificationDateKey 作为其中一个键。

  2. 您将获得一个NSURL对象数组,然后可以使用NSArray方法(如 -sortedArrayUsingComparator)对其进行排序:

  3. 传入比较器块,使用 -getResourceValue查找每个NSURL的修改日期:forKey:error:

  1. Call -contentsOfDirectoryAtURL:includingPropertiesForKeys:options:error: and specify NSURLContentModificationDateKey as one of the keys.
  2. You'll get back an array of NSURL objects which you can then sort using an NSArray method like -sortedArrayUsingComparator:.
  3. Pass in a comparator block that looks up the modification date for each NSURL using -getResourceValue:forKey:error:.

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

Update: When I wrote the answer above, -getResourceValue:forKey:error: existed in iOS but didn't do anything. That method is now functional as of iOS 5. The following code will log an app's resource files followed by a list of corresponding modification dates:

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);

这篇关于如何在iOS中按修改日期对文件进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆