把預先放在 bundle 裡的文字檔讀成字串,是相當基本卻常忘記語法的一件事。重點是:一定要指定編碼,並記得接 error 參數,否則出問題時完全無從查起。
NSError *error = nil;
NSString *textFileContents =
[NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"myTextFile" ofType:@"txt"]
encoding:NSUTF8StringEncoding
error:&error];
// 讀不到就代表出錯了
if (textFileContents == nil) {
NSLog(@"Error reading text file. %@", [error localizedFailureReason]);
}
NSArray *lines = [textFileContents componentsSeparatedByString:@"\n"];
NSLog(@"Number of lines in the file: %d", [lines count]);
幾個實務上的提醒:
pathForResource:ofType: 取得,不要自己拼 bundle 路徑。@"\n";不同平台產生的換行可能是 \r\n,跨平台時需一併處理。