出于某种原因,我编写的这个方法并没有摆脱目录中最旧的文件,即使从逻辑的角度来看一切似乎都很好。我错过了什么微妙的东西吗?
+(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];
}
我检查了错误,它总是(空)并且被删除的文件似乎是随机的 - 有时它是最新的,有时它是另一个。