ios - 删除目录 iOS 中最旧的文件

标签 ios

出于某种原因,我编写的这个方法并没有删除目录中最旧的文件,即使从逻辑角度来看一切似乎都很好。有什么我遗漏的微妙之处吗?

+(void)removeOldestFileFromDir:(NSURL *)dir forFileManager:(NSFileManager *)fm{
NSError *error = nil;
NSArray *contents = [fm contentsOfDirectoryAtPath:[dir path] error:&error];
NSArray *jpgFiles = [contents filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"self ENDSWITH '.jpg'"]];

NSDate *oldest = [NSDate date];
NSString *oldestFileName = nil;
for (NSString *f in jpgFiles) {
    NSString *photoPath = [[dir path] stringByAppendingPathComponent:f];

    NSDate *created = [[fm attributesOfItemAtPath:photoPath error:&error] objectForKey:@"NSFileCreationDate"];

    if([created compare:oldest] == NSOrderedAscending){
        oldestFileName = [NSString stringWithString:photoPath];
    }
}
[fm removeItemAtPath:oldestFileName error:&error];

}

我检查了错误,它总是 (null) 并且被删除的文件似乎是随机的 - 有时是最新的,有时是另一个。

最佳答案

您忘记在 if 中设置最旧的变量。

应该是这样的:

 if([created compare:oldest] == NSOrderedAscending){
        oldestFileName = [NSString stringWithString:photoPath];
        oldest = created; // !!! This is what is missing
   }

关于ios - 删除目录 iOS 中最旧的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15747777/

相关文章:

Javascript 在单元格单击时修改网页内容

ios - react native : how to get the names of all the albums

ios - 如何在 block 外部保持引用有效(启用ARC)?

ios - 如何自定义 Google Maps for iOS Swift 的 "myLocationButton"

ios - CocoaPods 在 Microsoft AppCenter for React Native 项目上安装失败

ios - 单例属性根据调用返回不同的值

ios - 仅将 4 行代码从 objective-c 转换为 swift(指针)

objective-c - 在 UIScrollview 中设置 size 属性

ios - 如何在字符的第一个实例之后剥离 NSString 的一部分?

ios - Xcode 本地化 - 如何为开发语言创建本地化字符串