Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/120.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
删除iOS目录中最旧的文件_Ios - Fatal编程技术网

删除iOS目录中最旧的文件

删除iOS目录中最旧的文件,ios,Ios,出于某种原因,我编写的这个方法并没有删除目录中最旧的文件,即使从逻辑角度看一切都很好。有什么微妙的东西我错过了吗 +(void)removeOldestFileFromDir:(NSURL *)dir forFileManager:(NSFileManager *)fm{ NSError *error = nil; NSArray *contents = [fm contentsOfDirectoryAtPath:[dir path] error:&error]; NSArray *jp

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

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

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

应该是这样的:

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

谢谢这可能是我所能犯的最愚蠢的错误,但幸好没什么比这更复杂的了,我开始认为iPhone编程只适合爱因斯坦。@SimonBarker:我们所有人都有:)谢谢!这可能是我所能犯的最愚蠢的错误,但幸好没什么比这更复杂的了,我开始认为iPhone编程只适合爱因斯坦。@SimonBarker:我们所有人都是这样:)