开发者

When to delete files in NSTemporaryDirectory

开发者 https://www.devze.com 2023-03-25 22:46 出处:网络
I am building a multitasking application which includes a functionality for开发者_开发技巧 viewing large pdf files. In order to avoid downloading the file each time the user wants to view the file, i

I am building a multitasking application which includes a functionality for开发者_开发技巧 viewing large pdf files. In order to avoid downloading the file each time the user wants to view the file, i download the file in the NSTemporaryDirectory and use the UIDocumentInteractionController to provide "Quick Look" and "Open in iBooks".

I wish to clear all temporary files when the user exits the application in order to avoid consuming space on user's device. Since my application is multitasking and my applicationWillTerminate method never gets called, the files are never deleted. When is it best to clear the NSTemporaryDirectory and how can i do it? Am i missing something?

Thanks in advance


You can make use of an old UNIX trick that also works fine on iOS (I know since I make use of it):

  • Save the files.
  • Open them.
  • Remember the filedescriptors.
  • Delete the files (this is the magic part).

The effect is that the files remain open as long as you don't close them. But their directory entries are gone, i.e. the files won't show up in a directory listing any more. The cool thing is now that as soon as you close one of those filedescriptors the corresponding file automatically gets completely deleted from disk. It doesn't matter whether you explicitly call close on them or whether your app terminates or crashes, in all those cases the files get deleted by the OS and you don't need to worry about it.

The downside is that you need to change your code so that it can work with the filedescriptors as you cannot access the files by name any longer.


applicationWillResignActive in your Appdelegate is the best place to do.

0

精彩评论

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

关注公众号