iOS開發(fā)之基礎(chǔ)篇(6)—— NSFileManager文件管理器

版本

Xcode 8.2.1

一、NSHomeDirectory()

目錄(Directories)在現(xiàn)在的操作系統(tǒng)里就是文件夾,而路徑(Path)則是包括盤符及一個(gè)或多個(gè)文件夾。

iOS每個(gè)APP都會(huì)有一個(gè)沙盒(Sandbox),用于存儲(chǔ)該APP所產(chǎn)生的資料內(nèi)容,如圖片、視頻、文件夾、plist文件等等。而這個(gè)沙盒的路徑可由NSHomeDirectory()得到,也叫APP的根目錄。根目錄下有四個(gè)文件/文件夾:

  • Documents 目錄:Apple官方建議將APP的重要數(shù)據(jù)保存到這個(gè)目錄下。因?yàn)閕Tunes備份時(shí)包括此目錄。
  • MyApp.app 目錄:這是APP本身。一般不要對(duì)其更改,否則啟動(dòng)時(shí)容易崩潰。
  • Library 目錄:該目錄下有兩個(gè)子目錄:Preferences和Caches;
    • Preferences:包含APP的偏好設(shè)置??捎肗SUserDefaults類來獲取或設(shè)置;
    • Caches:APP專用的支持文件,保存APP再次啟動(dòng)過程中需要的信息。
  • tmp 目錄:存放臨時(shí)文件,APP關(guān)閉后,該目錄下文件將被清除。

接下來我們小試一把,通過NSHomeDirectory()獲取APP的根目錄,并對(duì)其目錄路徑搞點(diǎn)小動(dòng)作。

int main(int argc, char * argv[]) {

    //獲取根目錄
    NSString *userPath = NSHomeDirectory();
    NSLog(@"path = %@",userPath);

    //拼接路徑
    NSString *newPath = [userPath stringByAppendingFormat:@"%@",@"/test"];
    NSLog(@"newPath = %@",newPath);

    //添加子路徑
    NSString *newPath2 = [userPath stringByAppendingPathComponent:@"test"];
    NSLog(@"newPath2 = %@",newPath2);

    //切割路徑x
    NSArray *resultPath = [userPath pathComponents];
    NSLog(@"resultPath = %@",resultPath);

    //再次拼接路徑
    NSString *newPath1 = [userPath stringByAppendingFormat:@"%@",@"/test/lalala.jpg"];
    NSLog(@"newPath1 = %@",newPath1);

    //獲取文件后綴名
    NSString *resultStr = [newPath1 pathExtension];
    NSLog(@"resultStr = %@",resultStr);

    //刪除后綴名
    NSString *resultPath1 = [newPath1 stringByDeletingPathExtension];
    NSLog(@"resultPath1 = %@",resultPath1);

    //刪除最后一個(gè)子路徑
    NSString *resultPath2 = [newPath1 stringByDeletingLastPathComponent];
    NSLog(@"resultPath2 = %@",resultPath2);
}

收獲如下:

獲取目錄路徑的方法小結(jié):

    // 獲取根目錄
    NSString *homeDir = NSHomeDirectory();
    NSLog(@"homeDir=%@", homeDir);
    // homeDir=/var/mobile/Containers/Data/Application/D3765F06-44E4-4B04-8CB0-2E92B7F07997
    
    // 獲取Documents目錄
    NSArray *docPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docDir = [docPaths objectAtIndex:0];
    NSLog(@"docDir=%@", docDir);
    // docDir=/var/mobile/Containers/Data/Application/D3765F06-44E4-4B04-8CB0-2E92B7F07997/Documents

    // 獲取Caches目錄
    NSArray *cachePaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cachesDir = [cachePaths objectAtIndex:0];
    NSLog(@"cachesDir=%@", cachesDir);
    // cachesDir=/var/mobile/Containers/Data/Application/D3765F06-44E4-4B04-8CB0-2E92B7F07997/Library/Caches
    
    // 獲取tmp目錄
    NSString *tmpDir = NSTemporaryDirectory();
    NSLog(@"tmpDir=%@", tmpDir);
    // tmpDir=/private/var/mobile/Containers/Data/Application/D3765F06-44E4-4B04-8CB0-2E92B7F07997/tmp/

注意:
使用NSTemporaryDirectory()方法獲取tmp目錄的時(shí)候, 后面多了一個(gè)/, 后面多了一個(gè)/, 后面多了一個(gè)/.

二、NSFileManager

對(duì)于這些文件路徑的操作(移動(dòng)、復(fù)制、連接或者刪除等等),往往會(huì)很雜亂,有時(shí)甚至?xí)僮鞒鲥e(cuò)。Apple為我們提供一個(gè)類,用于管理這些文件(路徑),是為——NSFileManager文件管理器。

NSFileManager類支持NSString和NSURL(往后再介紹)作為文件路徑。它還擁有一個(gè)代理協(xié)議NSFileManagerDelegate用來接收各種文件操作的通知,典型功用是當(dāng)錯(cuò)誤發(fā)生時(shí)可決定是否繼續(xù)。

NSFileManager可以在多個(gè)線程中安全調(diào)用,但問題是,如果創(chuàng)建了不一樣的NSFileManager實(shí)例對(duì)象,那么代理方法由誰來實(shí)現(xiàn)?別擔(dān)心,蘋果早就想好了——NSFileManager類的實(shí)例對(duì)象為單例。

所謂單例,即,不管你用這個(gè)類創(chuàng)建了多少個(gè)實(shí)例對(duì)象,這些對(duì)象實(shí)際上都是同一個(gè)(名稱雖不同,指針卻一樣)!下面舉例論證:

int main(int argc, char * argv[]) {
    //獲取文件管理器,單例對(duì)象:在整個(gè)應(yīng)用程序當(dāng)中,只會(huì)實(shí)例化一個(gè)這種類型的對(duì)象
    NSFileManager *manager = [NSFileManager defaultManager];
    NSLog(@"manager指針:%p",manager);
    //manager和manager1指針一樣,指向同一個(gè)對(duì)象
    NSFileManager *manager1 = [NSFileManager defaultManager];
    NSLog(@"manager1指針:%p",manager1);
}

我們不一樣?有啥不一樣:

前面介紹了獲取APP本身的一些目錄,下面為了方便查看結(jié)果,拷貝操作部分,我們將對(duì)桌面目錄試驗(yàn)NSFileManager。先在桌面放置一個(gè)plist文件,然后右鍵點(diǎn)“顯示簡介”,在“位置”那里得到路徑。續(xù)上代碼:

int main(int argc, char * argv[]) {
    //獲取文件管理器,單例對(duì)象:在整個(gè)應(yīng)用程序當(dāng)中,只會(huì)實(shí)例化一個(gè)這種類型的對(duì)象
    NSFileManager *manager = [NSFileManager defaultManager];
    NSLog(@"manager指針:%p",manager);
    //manager和manager1指針一樣,指向同一個(gè)對(duì)象
    NSFileManager *manager1 = [NSFileManager defaultManager];
    NSLog(@"manager1指針:%p",manager1);

    //獲取tmp目錄
    NSString *TmpDir = NSTemporaryDirectory();
    //拼接路徑
    NSString *TestDir = [TmpDir stringByAppendingFormat:@"%@",@"/test"];
    //fileExistsAtPath判斷此路徑是否已經(jīng)存在
    if(![manager fileExistsAtPath:TestDir]) {
        //先聲明一個(gè)NSError指針
        NSError *error = nil;
        //創(chuàng)建目錄----createDirectoryAtPath
        [manager createDirectoryAtPath:TestDir      //參數(shù)1: 創(chuàng)建的目錄路徑
           withIntermediateDirectories:YES          //參數(shù)2: 是否自動(dòng)添加缺失的路徑
                            attributes:nil          //參數(shù)3: 創(chuàng)建文件的附帶信息,一般為nil
                                 error:&error];     //參數(shù)4: 錯(cuò)誤信息;二級(jí)指針
        //如果存在error,就打印錯(cuò)誤信息
        if(error) {
            NSLog(@"error = %@",error);
        }
    }

    //淺層遍歷(遍歷根目錄第一層文件和文件夾)
    NSString *HomeDir = NSHomeDirectory();
    NSArray *resultArray = [manager contentsOfDirectoryAtPath:HomeDir error:nil];
    for(id obj in resultArray) {
        NSLog(@"淺層遍歷obj = %@",obj);
    }

    //深層遍歷(遍歷tmp路徑下的所有文件夾和文件)
    NSArray *resultArr1 = [manager subpathsOfDirectoryAtPath:HomeDir error:nil];
    for(id obj1 in resultArr1) {
        NSLog(@"深層遍歷obj = %@",obj1);
    }

    //創(chuàng)建一個(gè)桌面文件夾test
    NSString *desDir = @"/Users/tailor/Desktop/test";
    if(![manager fileExistsAtPath:desDir]) {
        NSError *error = nil;
        [manager createDirectoryAtPath:desDir
           withIntermediateDirectories:YES
                            attributes:nil
                                 error:&error];
        if(error) {
            NSLog(@"error = %@",error);
        }
    }

    //拷貝文件目錄
    NSString *srcPath = @"/Users/tailor/Desktop/Info.plist";
    NSString *dstPath1 = @"/Users/tailor/Desktop/Info1.plist";
    if(![manager copyItemAtPath:srcPath toPath:dstPath1 error:nil]) {
        NSLog(@"拷貝失敗");
    }

    //移動(dòng)/剪切
    NSString *dstPath2 = @"/Users/tailor/Desktop/test/Info2.plist";     //test必須存在,Info2.plist不存在(還沒創(chuàng)建)
    if(![manager moveItemAtPath:dstPath1 toPath:dstPath2 error:nil]) {
        NSLog(@"移動(dòng)失敗");
    }

    //刪除
    if(![manager removeItemAtPath:srcPath error:nil]) {
        NSLog(@"刪除失敗");
    }
}

結(jié)果如下:

對(duì)于copyItemAtPath: toPath:和moveItemAtPath: toPath:方法的一些操作,本人之前踩了許多坑,現(xiàn)在把它鋪平。先來看看官方文檔:

Discussion
If srcPath is a file, the method creates a file at dstPath that holds the exact contents of the original file (this includes BSD special files). If srcPath is a directory, the method creates a new directory at dstPath and recursively populates it with duplicates of the files and directories contained in srcPath, preserving all links. The file specified in srcPath must exist, while dstPath must not exist prior to the operation. When a file is being copied, the destination path must end in a filename—there is no implicit adoption of the source filename. Symbolic links are not traversed but are themselves copied. File or directory attributes—that is, metadata such as owner and group numbers, file permissions, and modification date—are also copied.

需要注意的信息有(無聊數(shù)了下有5個(gè)必須):

  1. 如果源路徑(srcPath)是文件,則目標(biāo)路徑(dstPath)必須是文件(且后綴名一致);
  2. 如果源路徑是文件夾,則目標(biāo)路徑必須是文件夾,將會(huì)復(fù)制源文件夾下所有文件(夾);
  3. 方法調(diào)用前,源路徑必須存在,目標(biāo)路徑必須不存在(注意:目 標(biāo)文件不存在,但目標(biāo)文件所在文件夾必須存在);
  4. 方法的一些錯(cuò)誤提示等。

三、后續(xù)

前面討論了使用NSFileManager創(chuàng)建目錄(文件夾), 其中withIntermediateDirectories:YES, 可以自動(dòng)添加缺失的路徑. 例如, 我們創(chuàng)建一個(gè)tmp/aaa/bbb目錄, 假如那個(gè)參數(shù)設(shè)置為NO, 則創(chuàng)建失敗, 因?yàn)闆]有aaa這個(gè)文件夾; 而如果設(shè)置為YES, 則系統(tǒng)自動(dòng)添加缺失的aaa文件夾路徑, 最終創(chuàng)建成功.
那么怎樣創(chuàng)建文件呢?
使用以下方法:

    NSString *filePath = [NSString stringWithFormat:@"%@%@", NSTemporaryDirectory(), @"123456.avi"];
    // 移除之前的
    [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
    // 創(chuàng)建文件
    if(![[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
        BOOL success = [[NSFileManager defaultManager] createFileAtPath:filePath    // 文件路徑
                                                               contents:nil         // 初始化的內(nèi)容
                                                             attributes:nil];       // 附加信息
        NSLog(@"success:%@, filePath=%@", success ? @"YES" : @"NO", filePath);
    }

注意:
創(chuàng)建文件方法和創(chuàng)建文件夾方法一大不同之處在于, 創(chuàng)建文件方法不能跨路徑創(chuàng)建文件. 比如說, 將上面的文件路徑改為"aaa/123456.avi", 由于多了aaa這個(gè)文件夾, 導(dǎo)致創(chuàng)建失敗. 也就是說, createFileAtPath:方法不會(huì)自動(dòng)添加缺失的文件夾路徑.

創(chuàng)建文件的正確姿勢(shì)

    NSFileManager *manager = [NSFileManager defaultManager];

    //獲取tmp目錄
    NSString *TmpDir = NSTemporaryDirectory();

    NSString *filePath = [NSString stringWithFormat:@"%@%@", TmpDir, @"abc/123456.avi"];
    // 移除之前的filePath
    [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
    // 創(chuàng)建文件夾
    NSString *folderPath = [filePath stringByDeletingLastPathComponent];    // 去除最后的組成部分 (/123456.avi)
    if(![manager fileExistsAtPath:folderPath]) {
        BOOL success = [manager createDirectoryAtPath:folderPath    //參數(shù)1: 創(chuàng)建的目錄路徑
                          withIntermediateDirectories:YES           //參數(shù)2: 是否自動(dòng)添加缺失的路徑
                                           attributes:nil           //參數(shù)3: 創(chuàng)建文件的附帶信息
                                                error:nil];         //參數(shù)4: 錯(cuò)誤信息
        NSLog(@"創(chuàng)建文件夾 success:%@, folderPath:%@", success ? @"YES" : @"NO", folderPath);
    }
    // 創(chuàng)建文件
    if(![manager fileExistsAtPath:filePath]) {
        BOOL success = [manager createFileAtPath:filePath    // 文件路徑
                                        contents:nil         // 初始化的內(nèi)容
                                      attributes:nil];       // 附加信息
        NSLog(@"success:%@, filePath=%@", success ? @"YES" : @"NO", filePath);
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,564評(píng)論 19 139
  • *面試心聲:其實(shí)這些題本人都沒怎么背,但是在上海 兩周半 面了大約10家 收到差不多3個(gè)offer,總結(jié)起來就是把...
    Dove_iOS閱讀 27,622評(píng)論 30 472
  • 一、iOS中的沙盒機(jī)制 iOS應(yīng)用程序只能對(duì)自己創(chuàng)建的文件系統(tǒng)讀取文件,這個(gè)獨(dú)立、封閉、安全的空間,叫做沙盒。它一...
    1d5cb7cff98d閱讀 1,873評(píng)論 0 0
  • 歲月留給女人的,不應(yīng)該僅僅是數(shù)不清的皺紋和蠟黃的膚色,異或一張無所顧忌的嘴…… 不知道為什么,因?yàn)橐?..
    一生女子閱讀 1,333評(píng)論 0 0
  • 在多線程情況下:多個(gè)線程要訪問同一塊資源時(shí),容易引發(fā)數(shù)據(jù)混亂出錯(cuò) 和線程安全等等問題。因此需要給線程加上互斥鎖。 ...
    summer_code閱讀 318評(píng)論 0 0

友情鏈接更多精彩內(nèi)容