我正在 iPhone 中编写内容。我用了这段代码
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filePath = [[paths objectAtIndex:0]stringByAppendingPathComponent"data.txt"];
NSString *temp = [[NSString alloc] initWithString"my name is gaurav"];
[temp writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
[temp release];
当我试图用这段代码用新内容覆盖这个文件时
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filePath = [[paths objectAtIndex:0]stringByAppendingPathComponent"data.txt"];
NSString *matter = [[NSString alloc] initWithString"Hello iPhone"];
[matter writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
[matter release];
如果我以原子方式传递 YES,则文件不会被覆盖。如果我在那里放置了否,则文件将被覆盖,但程序也会停止并退出。
[matter writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
Best Answer-推荐答案 strong>
我试过了。这是工作。您只需创建测试项目。并在 viewDidLod 方法中编写以下代码。并从文档目录中查看文本文件内容。它将被覆盖。
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filePath = [[paths objectAtIndex:0]stringByAppendingPathComponent"data.txt"];
NSString *temp = [[NSString alloc] initWithString"my name is gaurav"];
[temp writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
[temp release];
NSString *matter = [[NSString alloc] initWithString"Hello iPhone"];
[matter writeToFile:filePath atomically:NO encoding:NSUTF8StringEncoding error:nil];
[matter release];
}
关于iphone - 如何在 objective-c iphone的文本文件中写入内容,我们在Stack Overflow上找到一个类似的问题:
https://stackoverflow.com/questions/8645237/
|