iOS 的沙盒(sandbox)機制規定:每個應用程式只能存取自己應用目錄下的檔案,無法任意讀寫其他 App 或系統的資料。這與 Android 有 SD 卡可自由存取的模式有根本差異。
iOS 沒有對外可直接存取的共用儲存空間概念,App 產生的所有內容——圖片、文件、資料庫、快取——都必須存放在自己的沙盒內。這個設計帶來三個好處:應用之間不會互相干擾或竊取資料;使用者刪除 App 時系統能完整清除其殘留資料;出問題時影響範圍被限制在單一 App 內。
預設情況下,每個沙盒含有三個頂層目錄:Documents、Library 與 tmp。其中 Library 又包含 Caches 與 Preferences 等子目錄。
蘋果建議把「使用者產生的資料」與「App 瀏覽/下載而來、可再次生成的檔案」放在這裡。這個目錄會被 iTunes/Finder 備份與還原,使用者也能透過「檔案 App」或檔案共享功能看到它。因此不該把快取或暫存檔放進來。
存放程式的預設設定或其他狀態資訊。其中:
Library/Preferences:NSUserDefaults 的 plist 檔所在處。Library/Caches:存放快取檔案,用於應用關閉後仍需保留、但可隨時重新生成的持久化資料。這個目錄不會被 iTunes/iTunes 同步,因此若想縮短備份時間,可以考慮把體積較大又不需要備份的檔案放在這裡。系統在儲存空間不足時也可能自行清除它。提供一個臨時檔案的暫存處,不需要持久化。應用關閉後該目錄下的資料可能被刪除,系統也可能在 App 未執行時主動清理。
在模擬器上,完整路徑大致為:使用者 → 資源庫 → Application Support → iPhone Simulator → 7.1 → Applications(Xcode 6 之後路徑結構有變,詳見其他文章)。
#import "NSFileManagerViewController.h"
@interface NSFileManagerViewController ()
@end
@implementation NSFileManagerViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// 取得沙盒根目錄
NSString *dirHome = NSHomeDirectory();
NSLog(@"APP_home: %@", dirHome);
[self dirDoc];
[self dirLib];
[self dirCache];
[self dirTmp];
[self createDir];
[self createFile];
[self redFile];
[self fileAttriutes];
[self deleteFile];
}
// 取得 Documents 目錄路徑
- (NSString *)dirDoc
{
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [path objectAtIndex:0];
NSLog(@"app_home_doc: %@", documentsDirectory);
return documentsDirectory;
}
- (void)dirLib
{
NSArray *path = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,
NSUserDomainMask, YES);
NSString *libraryDirectory = [path objectAtIndex:0];
NSLog(@"app_home_lib: %@", libraryDirectory);
}
- (void)dirCache
{
NSArray *cacPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory,
NSUserDomainMask, YES);
NSString *cachePath = [cacPath objectAtIndex:0];
NSLog(@"app_home_cache: %@", cachePath);
}
- (void)dirTmp
{
NSString *tmpDirectory = NSTemporaryDirectory();
NSLog(@"app_home_tmp: %@", tmpDirectory);
}
// 建立資料夾
- (void)createDir
{
NSString *documentsPath = [self dirDoc];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *testDirectory = [documentsPath stringByAppendingString:@"test"];
BOOL res = [fileManager createDirectoryAtPath:testDirectory
withIntermediateDirectories:YES
attributes:nil
error:nil];
if (res) {
NSLog(@"文件夾創建成功");
} else {
NSLog(@"文件夾創建失敗");
}
}
// 建立檔案
- (void)createFile
{
NSString *documentPath = [self dirDoc];
NSString *testDirectory = [documentPath stringByAppendingPathComponent:@"test"];
NSFileManager *filemanager = [NSFileManager defaultManager];
NSString *testPath = [testDirectory stringByAppendingPathComponent:@"test.txt"];
BOOL res = [filemanager createFileAtPath:testPath contents:nil attributes:nil];
if (res) {
NSLog(@"文件創建成功:%@", testPath);
} else {
NSLog(@"文件創建失敗");
}
}
// 寫入檔案
- (void)writeFile
{
NSString *documentsPath = [self dirDoc];
NSString *testDirectory = [documentsPath stringByAppendingPathComponent:@"test"];
NSString *testPath = [testDirectory stringByAppendingPathComponent:@"test.txt"];
NSString *content = @"測試寫入內容!";
BOOL res = [content writeToFile:testPath
atomically:YES
encoding:NSUTF8StringEncoding
error:nil];
if (res) {
NSLog(@"文件寫入成功");
} else {
NSLog(@"文件寫入失敗");
}
}
// 讀取檔案
- (void)redFile
{
NSString *documentsPath = [self dirDoc];
NSString *testDirectory = [documentsPath stringByAppendingPathComponent:@"test"];
NSString *testPath = [testDirectory stringByAppendingPathComponent:@"test.txt"];
NSString *content = [NSString stringWithContentsOfFile:testPath
encoding:NSUTF8StringEncoding
error:nil];
NSLog(@"文件讀取成功: %@", content);
}
// 取得檔案屬性
- (void)fileAttriutes
{
NSString *documentsPath = [self dirDoc];
NSString *testDirectory = [documentsPath stringByAppendingPathComponent:@"test"];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *testPath = [testDirectory stringByAppendingPathComponent:@"test.txt"];
NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath:testPath error:nil];
NSArray *keys = [fileAttributes allKeys];
int count = (int)[keys count];
for (int i = 0; i < count; i++) {
id key = [keys objectAtIndex:i];
id value = [fileAttributes objectForKey:key];
NSLog(@"Key: %@ for value: %@", key, value);
}
}
// 刪除檔案
- (void)deleteFile
{
NSString *documentsPath = [self dirDoc];
NSString *testDirectory = [documentsPath stringByAppendingPathComponent:@"test"];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *testPath = [testDirectory stringByAppendingPathComponent:@"test.txt"];
BOOL res = [fileManager removeItemAtPath:testPath error:nil];
if (res) {
NSLog(@"文件刪除成功");
} else {
NSLog(@"文件刪除失敗");
}
NSLog(@"文件是否存在: %@",
[fileManager fileExistsAtPath:testPath] ? @"YES" : @"NO");
}
@end
範例最後用 isExecutableFileAtPath: 來判斷檔案是否存在,這是不對的——那個方法檢查的是「該檔案是否為可執行檔」。判斷存在性應該用 fileExistsAtPath:,上面的程式碼已修正。
另外 createDir 中原本用 stringByAppendingString: 拼接路徑,正確做法應是 stringByAppendingPathComponent:,因為前者不處理路徑分隔符號,在邊界情況會產生 .../testtest 這類錯誤路徑。
Documents。若要讓使用者能透過檔案 App 瀏覽,需在 Info.plist 設定 UIFileSharingEnabled 與 LSSupportsOpeningDocumentsInPlace。Library/Caches。tmp。使用後應自行刪除,不要指望系統何時清。NSUserDefaults(實體位於 Library/Preferences)。若某個檔案放在 Documents 或 Library 底下,預設會被 iCloud 備份。對於可重新下載的大量資料(例如離線地圖磚),應該把它標記為「不備份」,否則會快速吃滿使用者的 iCloud 空間並導致備份失敗:
NSURL *url = [NSURL fileURLWithPath:path];
NSError *error = nil;
BOOL success = [url setResourceValue:@(NO)
forKey:NSURLIsExcludedFromBackupKey
error:&error];
反過來說,tmp 與 Library/Caches 預設就不備份,不需要額外設定。