1. 程式人生 > >[ios2] iOS 5的檔案儲存策略應對【轉】

[ios2] iOS 5的檔案儲存策略應對【轉】

蘋果在iOS 5系統時,對app的檔案儲存提出了新的要求。從它的guildline來看,是推薦開發者儘量把app生成的檔案放在Caches目錄下的。原文如下:

Only user-generated data or that cannot otherwise be recreated by your application, should be stored in the /Documents directory and rest should be stored to /Library/Caches directory。

照做會怎麼樣?

如果這麼做的話,會出現兩種情況

  1. 如果對此置之不理,繼續把應用生成的檔案放在Documents目錄下,那麼這些檔案會被備份到iTunes或者iCloud。如果這些檔案很大,那麼使用者可能需要為了同步消耗不少流量,然後蘋果可能會因此拒絕你的應用上架,這是一個悲劇。
  2. 如果開發者照Apple說的幹,把應用生成的檔案放在Caches目錄下,那麼蘋果不會拒絕你的應用,很happy。但是iOS 5會在磁碟空間緊張的時候刪除Caches目錄下的檔案,這對使用者來說可能是一個更大的悲劇。

如何應對新的檔案儲存策略?

開發者在這時陷入了兩難的境地,但是到了iOS 5.0.1的時候,開發者多了第三種選擇:

  • 繼續把檔案儲存在Documents目錄下,但是標記這些檔案為不需要備份。詳情請參考 technote (QA1719)

原文如下:

Q: My app has a number of files that need to be stored on the device permanently for my app to function properly offline. However, those files do not contain user data and don’t need to be backed up. How should I store those files in iOS 5?

A: Starting in iOS 5.0.1 a new “do not back up” file attribute has been introduced allowing developers to clearly specify which files should be backed up, which files are local caches only and subject to purge, and which files should not be backed up but should also not be purged. In addition, setting this attribute on a folder will prevent the folder and all of its contents from being backed up.

程式碼示例

給檔案加上”do not back up”屬性的程式碼如下,需要注意這個是iOS 5.0.1才有效,低於這個版本就別費勁了。

#include<sys/xattr.h>-(BOOL)addSkipBackupAttributeToItemAtURL:(NSURL *)URL
{constchar* filePath =[[URL path] fileSystemRepresentation];constchar* attrName ="com.apple.MobileBackup";u_int8_t attrValue =1;int result = setxattr(filePath, attrName,&attrValue,sizeof(attrValue),0,0);return result ==0;}