版本
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個必須):
- 如果源路徑(srcPath)是文件,則目標路徑(dstPath)必須是文件(且后綴名一致);
- 如果源路徑是文件夾,則目標路徑必須是文件夾,將會復制源文件夾下所有文件(夾);
- 方法調用前,源路徑必須存在,目標路徑必須不存在(注意:目 標文件不存在,但目標文件所在文件夾必須存在);
- 方法的一些錯誤提示等。
三、后續
前面討論了使用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);
}