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

版本

Xcode 8.2.1

一、NSHomeDirectory()

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

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

  • Documents 目錄:Apple官方建議將APP的重要數據保存到這個目錄下。因為iTunes備份時包括此目錄。
  • MyApp.app 目錄:這是APP本身。一般不要對其更改,否則啟動時容易崩潰。
  • Library 目錄:該目錄下有兩個子目錄:Preferences和Caches;
    • Preferences:包含APP的偏好設置。可用NSUserDefaults類來獲取或設置;
    • Caches:APP專用的支持文件,保存APP再次啟動過程中需要的信息。
  • tmp 目錄:存放臨時文件,APP關閉后,該目錄下文件將被清除。

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

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);

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

收獲如下:

獲取目錄路徑的方法小結:

    // 獲取根目錄
    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目錄的時候, 后面多了一個/, 后面多了一個/, 后面多了一個/.

二、NSFileManager

對于這些文件路徑的操作(移動、復制、連接或者刪除等等),往往會很雜亂,有時甚至會操作出錯。Apple為我們提供一個類,用于管理這些文件(路徑),是為——NSFileManager文件管理器。

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

NSFileManager可以在多個線程中安全調用,但問題是,如果創建了不一樣的NSFileManager實例對象,那么代理方法由誰來實現?別擔心,蘋果早就想好了——NSFileManager類的實例對象為單例。

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

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

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

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

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

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

    //創建一個桌面文件夾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(@"拷貝失敗");
    }

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

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

結果如下:

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

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.

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

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

三、后續

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

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

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

創建文件的正確姿勢

    NSFileManager *manager = [NSFileManager defaultManager];

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

    NSString *filePath = [NSString stringWithFormat:@"%@%@", TmpDir, @"abc/123456.avi"];
    // 移除之前的filePath
    [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
    // 創建文件夾
    NSString *folderPath = [filePath stringByDeletingLastPathComponent];    // 去除最后的組成部分 (/123456.avi)
    if(![manager fileExistsAtPath:folderPath]) {
        BOOL success = [manager createDirectoryAtPath:folderPath    //參數1: 創建的目錄路徑
                          withIntermediateDirectories:YES           //參數2: 是否自動添加缺失的路徑
                                           attributes:nil           //參數3: 創建文件的附帶信息
                                                error:nil];         //參數4: 錯誤信息
        NSLog(@"創建文件夾 success:%@, folderPath:%@", success ? @"YES" : @"NO", folderPath);
    }
    // 創建文件
    if(![manager fileExistsAtPath:filePath]) {
        BOOL success = [manager createFileAtPath:filePath    // 文件路徑
                                        contents:nil         // 初始化的內容
                                      attributes:nil];       // 附加信息
        NSLog(@"success:%@, filePath=%@", success ? @"YES" : @"NO", filePath);
    }
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,739評論 6 534
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,634評論 3 419
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,653評論 0 377
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,063評論 1 314
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,835評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,235評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,315評論 3 442
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,459評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,000評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,819評論 3 355
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,004評論 1 370
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,560評論 5 362
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,257評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,676評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,937評論 1 288
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,717評論 3 393
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,003評論 2 374

推薦閱讀更多精彩內容

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