Jak*_*oni 3 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]];
Run Code Online (Sandbox Code Playgroud)
该程序在最后一行崩溃.有错误:
*由于未捕获的异常'NSUnknownKeyException'终止应用程序,原因:'[valueForUndefinedKey:]:此类不是密钥NSURLCreationDateKey的密钥值编码兼容.
编辑:更好的答案
如果这不起作用,您将必须编写自己的比较器块并获取手动比较的日期:(
[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];
}];
Run Code Online (Sandbox Code Playgroud)
(同样的免责声明仍然适用,但我甚至不确定会编译;) - 你明白了!)
这是我的第一个答案(包括在这里为后人,但大多数只是表明正确阅读问题是多么重要:)
这是因为你得到了一系列NSURL物体; 这些都没有NSURLCreationDateKey财产.
试试这个(免责声明 - 不是100%它会起作用)
NSString *key = [NSString stringWithFormat:@"fileAttributes.%@", NSURLCreationDateKey];
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:key ascending:YES];
Run Code Online (Sandbox Code Playgroud)
您的排序键是fileAttributes字典的属性,而该字典又是枚举器的属性.
| 归档时间: |
|
| 查看次数: |
3293 次 |
| 最近记录: |