版本
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è)置瞎颗。可用NSUserDefaults類來(lái)獲取或設(shè)置捌议;
- Caches:APP專用的支持文件哼拔,保存APP再次啟動(dòng)過(guò)程中需要的信息。
- tmp 目錄:存放臨時(shí)文件瓣颅,APP關(guān)閉后倦逐,該目錄下文件將被清除。
接下來(lái)我們小試一把宫补,通過(guò)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用來(lái)接收各種文件操作的通知鸳劳,典型功用是當(dāng)錯(cuò)誤發(fā)生時(shí)可決定是否繼續(xù)。
NSFileManager可以在多個(gè)線程中安全調(diào)用幸逆,但問題是棍辕,如果創(chuàng)建了不一樣的NSFileManager實(shí)例對(duì)象暮现,那么代理方法由誰(shuí)來(lái)實(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)“顯示簡(jiǎ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)在把它鋪平。先來(lái)看看官方文檔:
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.
需要注意的信息有(無(wú)聊數(shù)了下有5個(gè)必須):
- 如果源路徑(srcPath)是文件抹缕,則目標(biāo)路徑(dstPath)必須是文件(且后綴名一致)锦积;
- 如果源路徑是文件夾,則目標(biāo)路徑必須是文件夾歉嗓,將會(huì)復(fù)制源文件夾下所有文件(夾)丰介;
- 方法調(diào)用前,源路徑必須存在鉴分,目標(biāo)路徑必須不存在(注意:目 標(biāo)文件不存在哮幢,但目標(biāo)文件所在文件夾必須存在);
- 方法的一些錯(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)建文件. 比如說(shuō), 將上面的文件路徑改為"aaa/123456.avi", 由于多了aaa這個(gè)文件夾, 導(dǎo)致創(chuàng)建失敗. 也就是說(shuō), 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);
}