在 iOS 中操作檔案,蘋果已經封裝好了一個強大的類別——NSFileManager(檔案管理類),並開放對應的 API 供開發者使用。以下整理它最常見的幾個操作。
NSFileManager *manage = [NSFileManager defaultManager];
[manage createDirectoryAtPath:direcatorypath withIntermediateDirectories:YES attributes:nil error:nil];
此方法回傳 bool 型別,可直接判斷建立是否成功。
若要寫入 NSData 等資料:
BOOL isWrite = [_data writeToFile:filepath atomically:YES];
透過回傳值即可判斷是否寫入成功。
- (BOOL)copyItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath error:(NSError **)error;
- (BOOL)moveItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath error:(NSError **)error;
- (BOOL)removeItemAtPath:(NSString *)path error:(NSError **)error;
- (BOOL)fileExistsAtPath:(NSString *)path;
- (BOOL)isReadableFileAtPath:(NSString *)path;
掌握以上這些方法,就能應付日常絕大部分的檔案讀寫與管理需求。這些介面大多回傳 BOOL 或透過 NSError 回報結果,方便我們做出精準的錯誤處理。