按创建日期对NSURL对象数组进行排序

时间:2012-01-03 22:59:02

标签: iphone objective-c ios ios5

我将图像缓存到目录(/ Library / Caches / ImageCache /)。当目录超过一定大小时,我想删除目录中最旧的文件。要完成此任务,我使用NSFileManager来检索目录内容。然后我尝试按日期对此数组进行排序并删除最旧的对象。

我的问题是当我尝试通过密钥NSURLCreationDateKey对数组进行排序时,我的程序崩溃了。

NSFileManager *defaultFM = [NSFileManager defaultManager];
NSArray *keys = [NSArray arrayWithObjects:NSURLNameKey, NSURLCreationDateKey, nil];
NSURL *cacheDirectory = [self photoCacheDirectory];  // method that returns cache URL
NSArray *cacheContents = [defaultFM contentsOfDirectoryAtURL:cacheDirectory
                                  includingPropertiesForKeys:keys
                                                     options:NSDirectoryEnumerationSkipsSubdirectoryDescendants
                                                       error:nil];

NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:NSURLCreationDateKey ascending:YES];
NSArray *sortedArray = [cacheContents sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];

程序在最后一行崩溃。有错误:

* 由于未捕获的异常'NSUnknownKeyException'而终止应用程序,原因:'[valueForUndefinedKey:]:此类与密钥NSURLCreationDateKey不符合密钥值。'

2 个答案:

答案 0 :(得分:5)

编辑:更好的回答

如果这不起作用,您将必须编写自己的比较器块并获取手动比较的日期:(

[cacheContents sortUsingComparator:^ (NSURL *a, NSURL *b) {
    // get the two dates
    id da = [[a resourceValuesForKeys:[NSArray arrayWithObject:NSURLCreationDateKey] error:nil] objectForKey:NSURLCreationDateKey];
    id db = [[b resourceValuesForKeys:[NSArray arrayWithObject:NSURLCreationDateKey] error:nil] objectForKey:NSURLCreationDateKey];

    // compare them
    return [da compare:db];
}];

(同样的免责声明仍然适用,但我甚至不确定会编译;) - 你明白了!)


这是我的第一个答案(此处包含后代,但大多只是说明了正确阅读问题的重要性:)

这是因为你得到了一组NSURL个对象;这些没有NSURLCreationDateKey属性。

试试这个(免责声明 - 不是100%它会起作用)

NSString *key = [NSString stringWithFormat:@"fileAttributes.%@", NSURLCreationDateKey];
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:key ascending:YES];

您的排序键是fileAttributes字典的属性,而该字典又是枚举器的属性。

答案 1 :(得分:0)

我对此并不乐观,但我认为contentsOfDirectoryAtURL:方法返回的网址列表不是KVC对象。要从NSURL获得您想要的房产,您需要致电:

getResourceValue:forKey:error:

由于这不兼容KVC,因此您无法使用排序描述符,而是需要使用[cacheContents sortedArrayUsingComparator:...]

之类的例程。