删除目录iOS中最旧的文件

出于某种原因,我写的这个方法并没有摆脱目录中最旧的文件,即使从逻辑的angular度看,一切看起来都不错。 有什么微妙的我失踪?

+(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]; } 

我检查了错误,一直是(空),被删除的文件看起来是随机的 – 有时是最新的,有时是另一个。

你忘记在你的if里面设置最老的variables。

应该是这样的:

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