NSString 提供便利方法,無需手動管理串流。
NSError *error = nil;
NSMutableString *str = [NSMutableString string];
for (int i = 0; i < 10; ++i) {
[str appendString:@"你好!hello\n"];
}
BOOL success = [str writeToFile:@"/tmp/my.txt"
atomically:YES
encoding:NSUTF8StringEncoding
error:&error];
if (success) NSLog(@"success");
else NSLog(@"error: %@", [error localizedDescription]);
NSError *error = nil;
NSString *str = [[NSString alloc] initWithContentsOfFile:@"/tmp/my.txt"
encoding:NSUTF8StringEncoding
error:&error];
if (str) NSLog(@"content: %@", str);
else NSLog(@"error: %@", [error localizedDescription]);
NSData 封裝位元組陣列,適合圖片、序列化資料等。
NSError *error = nil;
NSData *data = [NSData dataWithContentsOfFile:@"/tmp/my.txt"];
BOOL success = [data writeToFile:@"/tmp/my2.txt"
options:NSDataWritingAtomic
error:&error];
if (success) NSLog(@"success");
else NSLog(@"error: %@", error);
atomically:YES 保證寫入原子性(先寫暫存檔再重命名)。NSError ** 回傳細節。無論文字或二進位,Cocoa 框架皆提供高層級、安全且易讀的 API。