0

出于某种原因,我编写的这个方法并没有摆脱目录中最旧的文件,即使从逻辑的角度来看一切似乎都很好。我错过了什么微妙的东西吗?

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

}

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

4

1 回答 1

3

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

它应该是这样的:

 if([created compare:oldest] == NSOrderedAscending){
        oldestFileName = [NSString stringWithString:photoPath];
        oldest = created; // !!! This is what is missing
   }
于 2013-04-01T17:23:51.483 回答