【问题标题】:How to remove Temporary Directory files fron iOS app?如何从 iOS 应用程序中删除临时目录文件?
【发布时间】:2012-03-28 14:05:51
【问题描述】:

我在使用设备时使用了删除临时目录文件的代码。

-(void) clearAllTempFiles {
    NSString *path = NSTemporaryDirectory();
    if ([path length] > 0)
    {
        NSError *error = nil;  
        NSFileManager *fileManager = [NSFileManager defaultManager];

        BOOL deleted = [fileManager removeItemAtPath:path error:&error];

        if (deleted != YES || error != nil)
        {

        }
        else{
            // Recreate the Documents directory
            [fileManager createDirectoryAtPath:path withIntermediateDirectories:NO attributes:nil error:&error];
        }

    }
}

它工作不正常?这是从临时目录中删除文件的正确代码吗?

请帮帮我?

【问题讨论】:

  • 我对模拟器的回答......
  • 您无权删除临时目录下的文件。该文件夹的权限是 drwx----- 所以你不要删除文件。

标签: iphone ios4 nsfilemanager


【解决方案1】:

我找到了一个简单的

NSArray* tmpDirectory = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:NSTemporaryDirectory() error:NULL];
for (NSString *file in tmpDirectory) {
    [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@%@", NSTemporaryDirectory(), file] error:NULL];
}

【讨论】:

    【解决方案2】:

    你可以在你的代码中使用这个来获取你 mac 上的 tmp 目录名称:

    代码:

    (void)cacheDirectory {
    
        NSString *tempPath = NSTemporaryDirectory();
    
        NSLog(@"Temp Value = %@", items);
    }
    

    从任何你想调用的方法。

    这将返回 tmp 文件夹名称,然后在 finder 中执行 (cmd-shift-G) 并粘贴您从控制台窗口获得的响应。

    下面会清空模拟器使用的TMP目录。

    代码:

    NSString *tempPath = NSTemporaryDirectory();
    NSArray *dirContents = [[NSFileManager defaultManager] directoryContentsAtPath:tempPath];
    NSArray *onlyJPGs = [dirContents filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"self ENDSWITH '.jpg'"]];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    if (onlyJPGs) { 
        for (int i = 0; i < [onlyJPGs count]; i++) {
        NSLog(@"Directory Count: %i", [onlyJPGs count]);
        NSString *contentsOnly = [NSString stringWithFormat:@"%@%@", tempPath, [onlyJPGs objectAtIndex:i]];
        [fileManager removeItemAtPath:contentsOnly error:nil];
    }
    

    上面的代码只清除目录中的 JPG,所以如果你想清除其他任何内容,请修改它。

    【讨论】:

    • 这是因为您的应用程序在后台进程中运行。如果您不想在 info.plist 文件中设置后台运行应用程序“应用程序不在后台运行”=YES
    • 我的问题是:当我停留在页面上的一页(登录屏幕)并按下主页按钮时,我有 3 页应用程序。我再次按下跳板上的应用程序图标,现在我不想显示登录屏幕,我想进入另一个屏幕(第二屏幕)。但是我的第一个屏幕(登录屏幕)出现在背景屏幕上,第二个屏幕为此目的而出现,我使用了 cleanallTempdirectoryfile?
    猜你喜欢
    • 1970-01-01
    • 2012-03-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-25
    • 2014-04-06
    • 1970-01-01
    • 1970-01-01
    • 2015-04-01
    相关资源
    最近更新 更多