什么时候清除iPhone应用程序缓存?

问题描述:

我正在开发一个应用程序,该应用程序使用户可以将语音(以及其他内容)记录到该应用程序的Documents目录中.但是,当我录制声音时,我将录制到应用程序的缓存目录中,然后在用户说好,保存此内容"之后,再将其处理到Documents目录中.到目前为止,所有这些工作.但是,如果我尝试删除缓存中的数据文件,或者当我尝试移动它时,就会遇到问题.

I'm working on an app that lets users record voice (among other things) to the Documents directory of the app. But when I'm recording the voice, I'm recording to the caches directory of the app and then after the user says "Okay, save this one", then I'm coping it to the Documents directory. So far all these work. But if I try to delete the data file in cache, or when I try to move it, I get problems.

所以我的问题是,我应该将数据保留在缓存中以便iOS处理它还是我需要手动删除缓存中的文件.如果是这样,我将如何去做.这是我到目前为止的代码(不起作用)

So my question is, shall I just leave the data in cache so that iOS will handle it or do I need to manually delete the files in cache. If so how would I go about doing it. This is the code I have so far (which doesn't work)

    NSFileManager *fm = [NSFileManager defaultManager];
    NSString *directory = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    NSError *error = nil;
    BOOL success = [fm removeItemAtPath:[NSString stringWithFormat:@"%@%@", directory, currentEntry.audioFileURL] error:&error];
    if (!success || error) {
        // it failed.
        NSLog(@"it failed to delete!!! %@ %@", error, [error userInfo]);
    } else {
        NSLog(@"Deleted... yipee... !!!");
    }

我认为问题在于您的路径不正确.始终使用

I think the problem is that your path is not correct. Always use the

- (NSString *)stringByAppendingPathComponent:(NSString *)aString

NSString的方法.

您可以尝试打印出您现在获得的路径(也许缺少反斜杠),但是无论如何,您都应该使用我描述的方法.

You can try printing out the path you get now (maybe a backslash is missing), but anyway you should use the method I described.

UPD:另一件事是NSCachesDirectory实际上从未清理过.如果要自动清洁,请使用NSTemporaryDirectory().

UPD: Another thing is that NSCachesDirectory is actually never cleaned up. Use NSTemporaryDirectory() if you want automatic cleaning.