黒毛和牛モモバラ切り落し100g298円

iPhoneアプリを作ってます。リリースノートとか用ブログです。

NSCachesDirectory と NSTemporaryDirectory に関するメモ

忘れそうなのでメモ。

それぞれがシステムから消されるタイミングは?

Apple のドキュメント File System Basics には、Caches ディレクトリは very low on disk space の時にシステムが消すことがあると書いてある。アプリが実行中には発生しないようなのでバックグラウンド起動中は発生するっぽい?

In iOS 5.0 and later, the system may delete the Caches directory on rare occasions when the system is very low on disk space. This will never occur while an app is running. However, be aware that restoring from backup is not necessarily the only condition under which the Caches directory can be erased.

同ドキュメントに Temporary ディレクトリの削除についても書いてあって、アプリが実行していない間に purge されると書いてある。

Use this directory to write temporary files that do not need to persist between launches of your app. Your app should remove files from this directory when they are no longer needed; however, the system may purge this directory when your app is not running.

Qiita とか stackoverflow だと、Caches はアプリ実行中に消されることがあって、Temporary は実行中に消されることは無いと書いてあることが多いんだけど、Apple のドキュメントを見る限り never occur while an app is running と when your app is not running なんで少なくともフォアグラウンド状態なら消されることは無いんじゃないですかね?

NSCachesDirectory ディレクトリのサブディレクト

Apple のドキュメント Accessing Files and Directories には、NSCachesDirectory の下に bundle_ID ディレクトリを作ってそこにファイル置いた方が良いと書かれている。

Use the Caches directory constant NSCachesDirectory, appending your <bundle_ID> directory for cached data files or any files that your app can re-create easily.

まったくもってその通りなんだけど、その辺適当にやってくれる便利メソッドあっても良いんじゃないですかねーという気が。ちなみに自分のアプリはこれやってたりやってなかったりで、ちょうどいじくってたアプリがやってなかったので OMG な感じでした。

なお bundle_ID は [[NSBundle mainBundle] bundleIdentifier] で取れる模様。

最後に全く関係ないですが、はてなブログMarkdown 使いにくいです。

追記

NSCachesDirectory の下に [[NSBundle mainBundle] bundleIdentifier] を作ると良いらしいと書いたが、実際のアプリには既にそのフォルダが存在している。何に使ってるか不明だが、そこには置かない方が良いようだ。