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

iOS 檔案操作與自訂物件歸檔/反歸檔完整教學

編輯:iOS 開發綜合

iOS 的檔案操作涵蓋建立、讀寫、移動與刪除。本文先整理基本 API,再示範如何把自訂類別的物件序列化存到檔案、之後再還原回來。

一、取得路徑與建立檔案

所有操作的第一步都是「先有路徑」。iOS 不建議寫死路徑,應透過 NSSearchPathForDirectoriesInDomains 取得沙盒目錄。

// Documents 目錄
NSString *strFilePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                            NSUserDomainMask, YES) objectAtIndex:0];
// 完整檔案路徑
NSString *fileName = [strFilePath stringByAppendingPathComponent:@"test.txt"];

NSFileManager *fmanager = [NSFileManager defaultManager];

// 檔案已存在就讀出來填進 textField
if ([fmanager fileExistsAtPath:fileName]) {
    self.txtField.text = [NSString stringWithContentsOfFile:fileName
                                                  encoding:NSUTF8StringEncoding
                                                     error:nil];
}

二、寫入

[self.txtField.text writeToFile:fileName
                    atomically:YES
                      encoding:NSUTF8StringEncoding
                         error:nil];
NSLog(@"儲存成功");

atomically 設為 YES 時,系統會先寫到暫存檔再改名,避免寫入中途被中斷而產生半截的壞檔。除了 NSString,NSDictionary 與 NSArray 也都能直接 writeToFile: 存成 plist。

三、讀取與確認存在

NSFileManager *fmanager = [NSFileManager defaultManager];
if ([fmanager fileExistsAtPath:fileName]) {
    // 檔案存在,可進行後續處理
}

四、移動

NSString *destPath = NSTemporaryDirectory();
NSString *destFilePath = [destPath stringByAppendingPathComponent:@"test.txt"];

BOOL result = [fmanager moveItemAtPath:fileName toPath:destFilePath error:nil];
NSLog(result ? @"移動成功" : @"移動失敗");

五、刪除

[[NSFileManager defaultManager] removeItemAtPath:fileName error:nil];

基本檔案操作小結

流程固定為三步:用 NSSearchPathForDirectoriesInDomains 取得目錄 → 組出完整路徑 → 透過 NSFileManager 實例執行各項操作。目錄選擇也有講究:Documents 會被 iCloud/iTunes 備份,Cache 則隨時可能被系統清掉,暫存檔案應該放 tmp。

自訂物件的歸檔與反歸檔

要讓自己的類別能被存進檔案,必須實作 NSCoding 協議。

步驟一:宣告類別並採用協議

#import <Foundation/Foundation.h>

@interface Person : NSObject <NSCoding>
@property (strong, nonatomic) NSString *name;
@property (nonatomic) int age;
- (instancetype)initWithName:(NSString *)name;
@end

步驟二:實作兩個協議方法

#import "Person.h"

@implementation Person

- (instancetype)initWithName:(NSString *)name {
    if (self = [super init]) {
        self.name = name;
    }
    return self;
}

#pragma mark - 序列化:物件 → 資料

- (void)encodeWithCoder:(NSCoder *)aCoder {
    [aCoder encodeObject:self.name forKey:@"name"];
    [aCoder encodeInt:self.age forKey:@"age"];
}

#pragma mark - 反序列化:資料 → 物件

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    if (self = [super init]) {
        self.name = [aDecoder decodeObjectForKey:@"name"];
        self.age  = [aDecoder decodeIntForKey:@"age"];
    }
    return self;
}

@end

這裡有個容易忽略的細節:initWithCoder: 中應該呼叫 [super init],而不是 [self init]。若誤寫成後者,在某些情境下會造成初始化流程不預期的遞迴。

步驟三:執行歸檔與反歸檔

- (void)viewDidLoad {
    [super viewDidLoad];

    Person *p = [[Person alloc] init];
    p.name = @"a";
    p.age  = 12;

    // ========== 歸檔(序列化) ==========
    // 1. 建立可變的二進位資料流
    NSMutableData *data = [[NSMutableData alloc] init];
    // 2. 建立歸檔物件
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
    // 3. 把自訂物件編碼進資料流
    [archiver encodeObject:p forKey:@"person"];
    // 4. 收尾
    [archiver finishEncoding];

    // 寫入檔案
    NSString *path = [NSTemporaryDirectory() stringByAppendingPathComponent:@"person.archive"];
    [data writeToFile:path atomically:YES];

    // ========== 反歸檔(反序列化) ==========
    NSData *mData = [NSData dataWithContentsOfFile:path];
    NSKeyedUnarchiver *unArchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:mData];
    Person *p2 = [unArchiver decodeObjectForKey:@"person"];
    NSLog(@"名字:%@", p2.name);
}

實務提醒

若 Person 內部還有其他自訂物件屬性,那些類別也必須一併實作 NSCoding,否則執行到該屬性時會拋出例外。

另外,若只是想把整個物件圖存成一個 plist,用 NSKeyedArchiver 的 archivedDataWithRootObject: 搭配 NSKeyedUnarchiver 的 unarchiveObjectWithData: 會更簡潔。新專案也可評估 NSCoding 的現代替代 NSSecureCoding,它會在解檔時驗證型別,避免反序列化攻擊——尤其在處理來自網路的資料時,這差別很重要。

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