开发者

How can we clear the cached images when we clos the app?

I cache the images to the document directory of my app using the following code.

NSArray *paths = NSSearchPa开发者_如何学运维thForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *saveDirectory = [paths objectAtIndex:0];

But even after I close the application, its still there. How can I clear it when I lose my app. I am doing all this in my simulator.


I would implement applicationWillTerminate: in my application delegate and remove the cache files there. Or better yet, as suggested by Vladimir, save them in a temporary directory and let the OS clean them up when needed.

- (void)applicationWillTerminate:(UIApplication *)app
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSArray *cacheFiles = [fileManager contentsOfDirectoryAtPath:saveDirectory error:error];
    for (NSString *file in cacheFiles) {
        error = nil;
        [fileManager removeItemAtPath:[saveDirectory stringByAppendingPathComponent:file] error:error];
        /* handle error */
    }
}


If you do not want your cached images to be preserved after application is closed better save them to temporary directory - they will be removed automatically.

If you want to manually remove the files you must store the paths for them and use the following NSFileManager function:

- (BOOL)removeItemAtPath:(NSString *)path error:(NSError **)error

Edit: sorry, I appeared to be wrong here about automatic deleting. Here's a quote from Developing Guide:
Use this directory to write temporary files that you do not need to persist between launches of your application. Your application should remove files from this directory when it determines they are no longer needed. (The system may also purge lingering files from this directory when your application is not running.)


NSString *file;
NSDirectoryEnumerator *dirEnum = [[NSFileManager defaultManager] enumeratorAtPath:saveDirectory];
NSError* err;
while (file = [dirEnum nextObject]) {
    err = nil;
    [[NSFileManager defaultManager] removeItemAtPath:[saveDirectory stringByAppendingPathComponent:file] error:&err]];
    if(err){
        //print some errror message
    }
}


Use the temporary directory path as specified in this question:

How can I get a writable path on the iPhone?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜