【问题标题】:NSData writeToFile not workingNSData writeToFile 不起作用
【发布时间】:2011-11-06 04:45:27
【问题描述】:

我似乎无法让 nsdata 写入文件。任何想法我可能做错了什么。提前致谢。

NSString* filename = @"myfile.txt";

NSString *applicationDocumentsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

NSString *storePath = [applicationDocumentsDir stringByAppendingPathComponent:filename];    

if ([fileManager fileExistsAtPath:applicationDocumentsDir])
    NSLog(@"applicationDocumentsDir exists");   // verifies directory exist

NSData *data = [NSData dataWithContentsOfURL:URL];

if (data) {    
     NSString *content = [[NSString alloc]  initWithBytes:[data bytes]
                                                      length:[data length] encoding: NSUTF8StringEncoding];

    NSLog(@"%@", content); // verifies data was downloaded correctly

    NSError* error;
    [data writeToFile:storePath options:NSDataWritingAtomic error:&error];

    if(error != nil)
        NSLog(@"write error %@", error);
}

我不断收到错误

"The operation couldn’t be completed. No such file or directory"

【问题讨论】:

  • 您不应该检查 error 是否为 nil - 它可以被初始化为任何东西(在您的情况下)。检查writeToFile:options:error 的结果以确定成功或失败。如果它返回 false (NO),那么你才应该读取错误。
  • 感谢您的回复。它返回 NO。我删除了检查以使帖子尽可能短。
  • 在调用 writeToFile:options:error: 之前,storePath 变量的值是多少?您的代码看起来不错,但您遇到的错误让我质疑该路径指向的位置。

标签: ios nsdata writetofile


【解决方案1】:

试试

NSString *storePath = [applicationDocumentsDir stringByAppendingPathComponent:@"myfile.txt"];

还有

 if ([[NSFileManager defaultManager] fileExistsAtPath:storePath])
        NSLog(@"applicationDocumentsDir exists");   

【讨论】:

  • 这样有效,很奇怪。字符串与 nsstring 变量有何不同。
  • 如果你把它打印出来,它有 file: 开头,它是一个 URL。我只是遇到了这个,即使我坚持使用字符串函数。
  • fileExistsAtPath 返回 false。该怎么办?因为它不存在,因为文件尚未创建。如何创建它?
【解决方案2】:

要获取更多信息,您可以使用

writeToFile:options:error:

而不是

writeToFile:原子地:

但您需要在执行写入之前在路径中创建所有子目录。像这样:

// if the directory does not exist, create it...
if ( [fileManager fileExistsAtPath:dir_path] == NO ) {
    if ( [fileManager createDirectoryAtPath:dir_path withIntermediateDirectories:NO attributes:NULL error:&error] == NO  ) {
        NSLog(@"createDirectoryAtPath failed %@", error);
    }
}

【讨论】:

    猜你喜欢
    • 2012-05-18
    • 2011-09-21
    • 2016-11-28
    • 2011-08-02
    • 1970-01-01
    • 1970-01-01
    • 2013-08-20
    • 1970-01-01
    • 2015-01-21
    相关资源
    最近更新 更多