NSFileManager不会删除临时文件夹中的文件

时间:2018-02-16 16:23:34

标签: ios objective-c nsfilemanager

我正在使用一个从互联网上下载图片并缓存它们的应用程序,以便在用户在图像之间来回切换时提高性能。

我想在UIViewController被解除时清除缓存文件夹。所以我创建了这个静态方法。但是,我不断收到错误:“文件无法删除”在每个文件上。

sDocumentsDir

/用户/ MYNAME /库/开发商/ CoreSimulator /设备/ E5FAB592-143A-4B04-9A8C-CFEA73E6C712 /数据/容器/数据/应用/ 2EB9CB73-9D34-4CE4-BA91-E9A3F2FC1CFA /文档/。 TMP

文件名如下所示:

HTTPS ___ s3.amazonaws.com_mycompany_1288c8be6f8101.jpg

我做错了什么?

+ (BOOL) clearCacheFolder {
    NSFileManager *filemgr = [NSFileManager defaultManager];
    NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *sDocumentsDir = [documentPaths objectAtIndex:0];
    sDocumentsDir = [sDocumentsDir stringByAppendingPathComponent:@"/.tmp"];

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"pathExtension == 'png' || pathExtension == 'jpg'"];

    BOOL isDir;
    if(([filemgr fileExistsAtPath:sDocumentsDir isDirectory:&isDir] && isDir)) {

        NSError *error;
        NSArray *fileArr = [filemgr contentsOfDirectoryAtPath:sDocumentsDir error:&error];
        if(error){
            NSLog(@"clearCacheFolder error populating array");
            return false;
        }

        NSLog(@"clearCacheFolder number of items to delete: %lu, files: %@",fileArr.count, fileArr.description);

        for(NSString *file in [fileArr filteredArrayUsingPredicate:predicate]){

            @try {
                [filemgr removeItemAtPath:[sDocumentsDir stringByAppendingString:file] error:&error];
            } @catch (NSException *exception) {
                NSLog(@"File delete exception: %@", exception.description);
            } @finally {
                if(error){
                    NSLog(@"File could NOT be deleted");
                } else {
                    NSLog(@"File Deleted");
                }
            }
        }

        fileArr = [filemgr contentsOfDirectoryAtPath:sDocumentsDir error:&error];
        NSLog(@"clearCacheFolder FINISHED count: %lu",fileArr.count);
    }
    return true;
}

1 个答案:

答案 0 :(得分:1)

检查您尝试使用的文件路径。 SELECT sku, count(distinct source_loc) inbound, count(distinct dest_loc) outbound, sum(case when dest_loc ='REC' then 1 else 0 end) recycle FROM skudata GROUP BY `sku` ORDER BY `sku`; 将生成错误的文件路径。 在你的例子中,它看起来像 /Users/MyName/Library/Developer/CoreSimulator/Devices/E5FAB592-143A-4B04-9A8C-CFEA73E6C712/data/Containers/Data/Application/2EB9CB73-9D34-4CE4-BA91-E9A3F2FC1CFA/Documents/.tmphttps___s3.amazonaws.com_mycompany_1288c8be6f8101。 JPG