NSFileManager 是 Foundation 框架中文件系統操作的核心類。本文演示兩種目錄遍歷方式:遞歸枚舉器(enumeratorAtPath:)與淺層列表(contentsOfDirectoryAtPath:)。
| 方法 | 遍歷深度 | 返回類型 | 適用場景 |
|---|---|---|---|
enumeratorAtPath: | 遞歸(子目錄) | NSDirectoryEnumerator | 深度掃描、查找文件 |
contentsOfDirectoryAtPath: | 僅當前目錄 | NSArray | 列表展示、非遞歸需求 |
#importint main(int argc, const char *argv[]) { @autoreleasepool { NSFileManager *fm = [NSFileManager defaultManager]; // 1. 獲取當前工作目錄 NSString *cwd = [fm currentDirectoryPath]; NSLog(@"當前目錄: %@", cwd); // 2. 遞歸枚舉器遍歷 NSDirectoryEnumerator *dirEnum = [fm enumeratorAtPath:cwd]; NSString *path; NSLog(@"=== 遞歸枚舉 ==="); while ((path = [dirEnum nextObject]) != nil) { NSLog(@"%@", path); } // 3. 淺層列表 NSArray *shallow = [fm contentsOfDirectoryAtPath:cwd error:NULL]; NSLog(@"=== 淺層列表 ==="); for (path in shallow) { NSLog(@"%@", path); } // 4. 指定路徑列表 (家目錄) NSArray *home = [fm contentsOfDirectoryAtPath:@"/Users/fansunion" error:NULL]; NSLog(@"=== 家目錄 ==="); NSLog(@"%@", home); } return 0; }
2015-11-29 13:02:49.528 FilePath[2750:159478] 當前目錄: /Users/fansunion/Library/Developer/Xcode/DerivedData/FilePath-dfjiajapcipfrbcbfjmxijqhscws/Build/Products/Debug
2015-11-29 13:02:49.534 FilePath[2750:159478] === 遞歸枚舉 ===
FilePath
2015-11-29 13:02:49.534 FilePath[2750:159478] === 淺層列表 ===
FilePath
2015-11-29 13:02:49.535 FilePath[2750:159478] === 家目錄 ===
(
".bash_history",
".CFUserTextEncoding",
".DS_Store",
".ssh",
".subversion",
".Trash",
Desktop,
Documents,
Downloads,
Library,
Movies,
Music,
Pictures,
Public
)
currentDirectoryPath 指向產物而非源碼目錄/Users/fansunion 展示典型 macOS 用戶目錄結構. 開頭)默認包含在列表中// 在枚舉器中獲取文件詳細信息 NSDictionary *attrs = [dirEnum fileAttributes]; NSFileType type = [attrs fileType]; NSUInteger size = [attrs fileSize]; NSDate *modDate = [attrs fileModificationDate]; BOOL isDir = (type == NSFileTypeDirectory);
六、錯誤處理最佳實踐
NSError ** 參數捕獲失敗原因nil 而非異常(Foundation 不拋出異常)NSError 返回NSString 路徑方法(stringByAppendingPathComponent: 等)而非手動拼接