由于某种原因,我写的这个方法并没有摆脱目录中最旧的文件,即使从逻辑的角度来看一切都很好。我有什么微妙的遗失吗?
+(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)并且删除的文件看起来是随机的 - 有时它是最新的,有时它是另一个。
答案 0 :(得分:3)
您忘记在if。
中设置最旧的变量应该是这样的:
if([created compare:oldest] == NSOrderedAscending){
oldestFileName = [NSString stringWithString:photoPath];
oldest = created; // !!! This is what is missing
}