【问题标题】:how to write content in text file in objective C iphone如何在目标C iphone的文本文件中写入内容
【发布时间】:2011-12-27 13:37:03
【问题描述】:

我正在 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];

【问题讨论】:

  • 另外,您在使用通过NSError 提供详细错误报告的方法时遇到问题,但您未能检查该错误。
  • 你必须将你的字符串转换为 NSData

标签: iphone objective-c ios file-io filesystems


【解决方案1】:

我试过了。这是工作。您只需创建测试项目。并在 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];

}

【讨论】:

    猜你喜欢
    • 2012-10-12
    • 1970-01-01
    • 2017-07-13
    • 2020-06-30
    • 2022-01-09
    • 1970-01-01
    • 2011-03-05
    • 2014-04-07
    • 2012-02-19
    相关资源
    最近更新 更多