萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> iOS 開發

iOS 讀取 Bundle 文本文件到字符串:一行代碼與完整錯誤處理

最簡單方式(同步、主線程可用於小文件)


// Objective-C
NSError *error = nil;
NSString *path = [[NSBundle mainBundle] pathForResource:@"myTextFile" ofType:@"txt"];
NSString *content = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
if (error) {
    NSLog(@"❌ 讀取失敗:%@", error.localizedDescription);
} else {
    NSLog(@"✅ 內容長度:%lu", (unsigned long)content.length);
}

// Swift
if let path = Bundle.main.path(forResource: "myTextFile", ofType: "txt") {
    do {
        let content = try String(contentsOfFile: path, encoding: .utf8)
        print("✅ 字符數:\(content.count)")
    } catch {
        print("❌ 讀取失敗:\(error)")
    }
}

按行分割處理


// OC
NSArray *lines = [content componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
NSLog(@"行數:%lu", (unsigned long)lines.count);

// Swift
let lines = content.components(separatedBy: .newlines)
print("行數:\(lines.count)")

大文件/異讀取(避免阻塞主線程)


// OC - NSFileHandle 分塊讀取
NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:path];
NSData *chunk;
while ((chunk = [handle readDataOfLength:4096]).length > 0) {
    NSString *part = [[NSString alloc] initWithData:chunk encoding:NSUTF8StringEncoding];
    // 流式處理...
}
[handle closeFile];

// Swift - FileHandle / AsyncSequence (iOS 15+)
let handle = FileHandle(forReadingAtPath: path)!
for try await line in handle.bytes.lines {
    // 處理每行
}
try handle.close()

常見編碼陷阱

場景編碼參數說明
標準 UTF-8NSUTF8StringEncoding / .utf8現代默認,支援中文/Emoji
GBK/GB2312 (舊中文系統)CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000)需 CoreFoundation,Swift 用 String.Encoding(rawValue:)
UTF-16NSUTF16StringEncoding / .utf16較少見
自動檢測NSStringEncodingDetectionOptionsKeyNSData -> NSString 可嘗試自動檢測

文件位置最佳實踐

  • 只讀資源:放入 Xcode 工程 → Copy Bundle Resources → [[NSBundle mainBundle] pathForResource:ofType:]
  • 可寫數據:NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject (Documents 目錄,備份上傳)
  • 緩存文件:NSCachesDirectory (可被系統清理)
  • 臨時文件:NSTemporaryDirectory() (App 重啟可能清理)

調試技巧


// 列出 Bundle 所有資源
NSArray *all = [[NSBundle mainBundle] pathsForResourcesOfType:@"txt" inDirectory:nil];
NSLog(@"Bundle txt files: %@", all);

// 實時查看沙盒路徑
NSLog(@"Documents: %@", NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0]);
copyright © 萬盛學電腦網 all rights reserved