gpt4 book ai didi

objective-c - 如何在不覆盖 objective-c 的情况下保存文本文件

转载 作者:行者123 更新时间:2023-11-29 13:36:42 25 4
gpt4 key购买 nike

我正在尝试将 NSString 写入文件。它正在成功写入,但是我想将新字符串附加到新行。

如何做到这一点?

最佳答案

您可以读取文件内容,将新数据附加到该内容并将新数据保存到您使用的文件中:

// Here you set your appending text.    
NSString *yourAppendingText = @"yourAppendingText";

// Here you get access to the file in Documents directory of your application bundle.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDir = [paths objectAtIndex:0];
NSString *documentFile = [documentDir stringByAppendingPathComponent:@"yourFile.txt"];

// Here you read current existing text from that file
NSString *textFromFile = [NSString stringWithContentsOfFile:documentFile encoding:NSUTF8StringEncoding error:nil];
// Here you append new text to the existing one
NSString *textToFile = [textFromFile stringByAppendingString:yourAppendingText];
// Here you save the updated text to that file
[textToFile writeToFile:documentFile atomically:YES encoding:NSUTF8StringEncoding error:nil];

关于objective-c - 如何在不覆盖 objective-c 的情况下保存文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10407858/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com