iOS開發之沙盒機制&文件操作(NSFielManager)

沙盒機制

iOS APP可以在自己的沙盒里讀寫文件,但是,不可以訪問其他APP的沙盒。每一個APP都是一個信息孤島,相互是不可以進行通信的,唯獨可以通過URL Scheme。沙盒里面的文件可以是照片、聲音文件、文本、屬性列表等。

沙河盒根目錄的結構
  • Documents:用于存儲用戶數據,iTunes備份和恢復的時候會包含此目錄。所以,蘋果建議將程序中建立的或在程序中瀏覽到的數據保存在該目錄下
  • Library
    • Caches :Caches用來存放用戶需要換成的文件
    • Preferences :Preferences是APP的偏好設置,可以通過NSUserDefaults來讀取和設置
  • tmp:用于存放臨時文件,這個可以放一些當APP退出后不再需要的文件。
62317-e49c692cb5d9ebb3.png
路徑獲取
1、獲取沙盒根目錄
NSString *directory = NSHomeDirectory();
    NSLog(@"directory:%@", directory);

打印結果

directory:/Users/jiangjunuhi/Library/Developer/CoreSimulator/Devices/66637C61-6E6B-4564-88A0-203CA75FDC83/data/Containers/Data/Application/09AB2635-9FAA-4B5A-A7BE-1ADF25391A03
2、獲取Documents路徑

參數的意義:

21BD09BC-4F15-4FDD-AF3E-A5D3FA2EF2BB.png
 /*
     第一個參數:指定了搜索的路徑的名稱:NSDocumentDirectory 表示是在Documents中尋找。NSCacheDirectory的話就是在cache文件中尋找
     第二個參數:第二個參數限定了文件的檢索范圍只在沙箱內部.其意義為用戶電腦主目錄.也可以修改為網絡主機等
     第三個參數:最后一個參數決定了是否展開波浪線符號.展開后才是完整路徑,這個布爾值一直為YES.
     */
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSLog(@"paths.count:%ld",paths.count);
    for (NSInteger i = 0; i < paths.count; i++) {
        NSString *path = paths[i];
        NSLog(@"path:%@",path);
    }

打印結果:

0C469A95-2A42-41C4-AA77-2EB6D97917E2.png

打印的路徑

path:/Users/jiangjunuhi/Library/Developer/CoreSimulator/Devices/66637C61-6E6B-4564-88A0-203CA75FDC83/data/Containers/Data/Application/3EAAAB22-F3B3-40E8-84BC-34380BBF0AC1/Documents
3、獲取Library路徑
 //獲取Library路徑
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *path = [paths objectAtIndex:0];
NSLog(@"path:%@", path);

打印結果

path:/Users/jiangjunuhi/Library/Developer/CoreSimulator/Devices/66637C61-6E6B-4564-88A0-203CA75FDC83/data/Containers/Data/Application/87028E4A-2AEC-4CEE-8743-DA087A41B3B7/Library
4、獲取Caches路徑
//獲取Caches路徑
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *path = [paths objectAtIndex:0];
NSLog(@"path:%@", path);

打印結果

path:/Users/jiangjunuhi/Library/Developer/CoreSimulator/Devices/66637C61-6E6B-4564-88A0-203CA75FDC83/data/Containers/Data/Application/5C10AF1E-9B02-4A72-93A2-52CAC2C17326/Library/Caches
5、獲取tmp路徑
NSString *tmp = NSTemporaryDirectory();
NSLog(@"tmp:%@", tmp);

打印結果

tmp:/Users/jiangjunuhi/Library/Developer/CoreSimulator/Devices/66637C61-6E6B-4564-88A0-203CA75FDC83/data/Containers/Data/Application/B68EE6BA-BE71-4315-AEB5-3C84237BAB28/tmp/
打開沙盒方法

finder前往

屏幕快照 2017-04-12 上午11.11.28.png

直接在Finder->前往->前往文件夾,輸入上面的內容即可

文件操作

NSFileManager:NSFileManager是用來管理文件系統的,它可以用來進行常見的文件\文件夾操作(拷貝、剪切、創建等)

NSFileManager使用了單例模式singleton
使用defaultManager方法可以獲得那個單例對象
[NSFileManager defaultManager]

文件的增刪改查
1、創建文件夾
 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsPath = [paths objectAtIndex:0];
    
    //創建文件夾的路徑
    NSString *testPath = [documentsPath stringByAppendingPathComponent:@"test"];
    //創建目錄
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL rest = [fileManager createDirectoryAtPath:testPath withIntermediateDirectories:YES attributes:nil error:nil];
    if (rest) {
        NSLog(@"文件夾創建成功:%@",testPath);
    }else{
        NSLog(@"文件夾創建失敗");
    }

打印結果

文件夾創建成功:/Users/jiangjunuhi/Library/Developer/CoreSimulator/Devices/66637C61-6E6B-4564-88A0-203CA75FDC83/data/Containers/Data/Application/FC2F96A3-A5A6-4BC9-A551-204F9F247F9D/Documents/test
2、創建文件
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsPath = [paths objectAtIndex:0];

    NSString *testDirectory = [documentsPath 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(@"文件創建失敗");
    }

打印結果

文件創建成功: /Users/jiangjunuhi/Library/Developer/CoreSimulator/Devices/66637C61-6E6B-4564-88A0-203CA75FDC83/data/Containers/Data/Application/43303432-330A-4845-A674-F4B74FC81E67/Documents/test/test.txt
3、寫數據到文件
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsPath = [paths objectAtIndex:0];

    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(@"文件寫入成功:%@",testPath);
    }else
        NSLog(@"文件寫入失敗");
    
4、讀文件數據
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsPath = [paths objectAtIndex:0];
NSString *testDirectory = [documentsPath stringByAppendingPathComponent:@"test"];  
    NSString *testPath = [testDirectory stringByAppendingPathComponent:@"test.txt"];  
//    NSData *data = [NSData dataWithContentsOfFile:testPath];  
//    NSLog(@"文件讀取成功: %@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);  
    NSString *content=[NSString stringWithContentsOfFile:testPath encoding:NSUTF8StringEncoding error:nil];  
    NSLog(@"文件讀取成功: %@",content);
5、刪除文件
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
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 isExecutableFileAtPath:testPath]?@"YES":@"NO");  
}  
2、文件的一些常用方法
1、判斷文件是否存在
 //創建文件管理對象
    //調用defaultManager 創建一個文件管理的單例對象
    //單例對象:在程序運行期間,只有一個對象存在
    NSFileManager *fm = [NSFileManager defaultManager];
    // YES 存在   NO 不存在
    BOOL isYES = [fm fileExistsAtPath:filePath];
    NSLog(@"-->%d",isYES);
2、判斷是否是一個目錄
if(isYES){
        BOOL isDir;

        // 2) 判斷是否是一個目錄
        [fm fileExistsAtPath:filePath isDirectory:&isDir];

        if (isDir) {
            NSLog(@"這是一個目錄");
        }else{

            NSLog(@"這不是一個目錄");
        }

    }
3、判斷文件是否可讀
[fm isReadableFileAtPath:filePath];
4、是否可寫
[fm isWritableFileAtPath:filePath2];
5、是否可刪除
[fm isDeletableFileAtPath:filePath2];
6、獲取文件的信息(屬性)
//創建文件對象
    NSFileManager *fm = [NSFileManager defaultManager];
    NSString *filePath = @"/Users/zhaoxiaohu/Desktop/arr.plist";

    NSString *dirPath = @"/Users/zhaoxiaohu/Desktop/a";

    //1)如何獲取文件的信息(屬性)
    NSDictionary *dict = [fm attributesOfItemAtPath:filePath error:nil];
    NSLog(@"%@",dict);
    NSLog(@"%@,%@",[dict objectForKey:@"NSFileOwnerAccountName"],dict[@"NSFileOwnerAccountName"]);
7、copy文件
 //如何copy文件
    NSString *targetPath = @"/Users/zhaoxiaohu/Desktop/aaa/ccc/love.txt";
    [fm copyItemAtPath:createDirPath toPath:targetPath error:nil];

     NSString *targetPath = @"/Users/zhaoxiaohu/Desktop/aaa/love.txt";
8、移動文件
 [fm moveItemAtPath:createDirPath toPath:targetPath error:nil];
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容