加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Swift 2 iOS – 按创建日期排序的文件列表 – 更简洁的解决方案

发布时间:2020-12-14 05:19:03 所属栏目:百科 来源:网络整理
导读:在我的代码中,我正在返回一个[String]?包含存储在/ Documents / – 的文件名(lastPathComponent),按照上次修改的日期排序. 我相信我可能使用太多的步骤,并在这里寻找建议,如何减少代码. 为了达到目前所需的结果 – 我正在创建两个中间词典:var attributesD
在我的代码中,我正在返回一个[String]?包含存储在/ Documents / – 的文件名(lastPathComponent),按照上次修改的日期排序.

我相信我可能使用太多的步骤,并在这里寻找建议,如何减少代码.

为了达到目前所需的结果 – 我正在创建两个中间词典:var attributesDictionary:[String:AnyObject]?和var urlDictionary = [NSURL:NSDate]().循环通过初始[NSURL]我使用两个步骤 – .resourceValuesForKeys初始化attributesDictionary.然后填入urlDictionary,使其包含URL和NSURLContentModificationDateKey关键字的值.

我觉得应该有一种方法来实现这个结果,而不必创建urlDictionary和attributesDictionary,而不需要循环.也许从urlArray直接.这是我当前的代码:

编辑:Arthur Gevorkyan在第一条评论中指出,do {}不是必需的.

func getFileList() -> [String]? {
    let directory = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory,inDomains: .UserDomainMask)[0]
    let properties = [NSURLLocalizedNameKey,NSURLCreationDateKey,NSURLContentModificationDateKey,NSURLLocalizedTypeDescriptionKey]

    // no catch required - contentsOfDirectoryAtURL returns nil if there is an error
    if let urlArray = try? NSFileManager.defaultManager().contentsOfDirectoryAtURL(directory,includingPropertiesForKeys: properties,options:NSDirectoryEnumerationOptions.SkipsHiddenFiles) {
        var attributesDictionary: [String:AnyObject]?
        var dateLastModified: NSDate
        var urlDictionary = [NSURL:NSDate]()

        for URLs in urlArray {
            // no catch required - resourceValuesForKeys returns nil if there is an error
            attributesDictionary = try? URLs.resourceValuesForKeys(properties)
            dateLastModified = attributesDictionary?[NSURLContentModificationDateKey] as! NSDate
            urlDictionary[URLs] = dateLastModified
        }
        // this approach to sort is used because NSDate cannot be directly compared with </>
        return urlDictionary.filter{$0 != nil}.sort{$0.1.compare($1.1) == NSComparisonResult.OrderedDescending }.map{$0.0}.map{$0.lastPathComponent!}
    } else {
        return nil
    }
}
可能的解决方案:
if let urlArray = try? NSFileManager.defaultManager().contentsOfDirectoryAtURL(directory,options:.SkipsHiddenFiles) {

    return urlArray.map { url -> (String,NSTimeInterval) in
        var lastModified : AnyObject?
        _ = try? url.getResourceValue(&lastModified,forKey: NSURLContentModificationDateKey)
        return (url.lastPathComponent!,lastModified?.timeIntervalSinceReferenceDate ?? 0)
    }
    .sort({ $0.1 > $1.1 }) // sort descending modification dates
    .map { $0.0 } // extract file names

} else {
    return nil
}

URL数组首先映射到(lastPathComponent,lastModificationDate)元组的数组,然后按照
最后修改日期,最后提取路径名.

attributesDictionary可以通过使用来避免
getResourceValue(_:forKey)仅检索最后一个修改日期.

Swift 3的更新:

let directory = FileManager.default.urls(for: .documentDirectory,in: .userDomainMask).first!
if let urlArray = try? FileManager.default.contentsOfDirectory(at: directory,includingPropertiesForKeys: [.contentModificationDateKey],options:.skipsHiddenFiles) {

    return urlArray.map { url in
            (url.lastPathComponent,(try? url.resourceValues(forKeys: [.contentModificationDateKey]))?.contentModificationDate ?? Date.distantPast)
        }
        .sorted(by: { $0.1 > $1.1 }) // sort descending modification dates
        .map { $0.0 } // extract file names

} else {
    return nil
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读