您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 中檔案的讀與寫:NSFileManager 用法整理

編輯:iOS 開發綜合

在 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 回報結果,方便我們做出精準的錯誤處理。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved