【问题标题】:ios file write is not workingios文件写入不起作用
【发布时间】:2016-04-08 13:42:19
【问题描述】:

我想在文件中写入一个简单的数据,但它不起作用。

- (void)writeStringToFile:(NSString*)aString {

    // Build the path, and create if needed.
    NSString* filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString* fileName = @"bookmark.json";
    NSString* fileAtPath = [filePath stringByAppendingPathComponent:fileName];
    NSLog(@"%@",fileAtPath);
    if (![[NSFileManager defaultManager] fileExistsAtPath:fileAtPath]) {
        [[NSFileManager defaultManager] createFileAtPath:fileAtPath contents:nil attributes:nil];
    }

    // The main act...
    [[aString dataUsingEncoding:NSUTF8StringEncoding] writeToFile:fileAtPath atomically:YES];
}

【问题讨论】:

  • 你怎么知道它不起作用?
  • 您的代码在我看来不错,但是没有错误报告。使用[NSData writeToFile:options:error:] 并检查返回码并记录错误对象。
  • 为什么你有那个if 声明,你为什么打电话给createFileAtPath?你也不需要。只需致电writeToFile:options:error:
  • hi没有找到任何文件名bookmark.json

标签: ios objective-c nsfilemanager


【解决方案1】:

您仍然可以修改应用程序的文档目录。

检查文件是否存在于路径中

 NSFileManager *fileManager = [NSFileManager defaultManager];
 //Get documents directory
 NSArray *directoryPaths = NSSearchPathForDirectoriesInDomains
 (NSDocumentDirectory, NSUserDomainMask, YES);
 NSString *documentsDirectoryPath = [directoryPaths objectAtIndex:0];
 if ([fileManager fileExistsAtPath:@""]==YES) {
     NSLog(@"File exists");
 }    

检查是否可写、可读和可执行

if ([fileManager isWritableFileAtPath:@"FilePath"]) {
    NSLog(@"isWritable");
 }
 if ([fileManager isReadableFileAtPath:@"FilePath"]) {
    NSLog(@"isReadable");
 }
 if ( [fileManager isExecutableFileAtPath:@"FilePath"]){
    NSLog(@"is Executable");
 }

试试这个 Link

快乐编码 (^_^)

【讨论】:

    【解决方案2】:

    试试这样......

      - (void)writeStringToFile:(NSString*)aString {
    
    // Build the path, and create if needed.
    NSString* filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString* fileName = @"bookmark.json";
    NSString* fileAtPath = [filePath stringByAppendingPathComponent:fileName];
    NSLog(@"%@",fileAtPath);
    if (![[NSFileManager defaultManager] fileExistsAtPath:fileAtPath]) {
        // The main act...
    [[aString dataUsingEncoding:NSUTF8StringEncoding] writeToFile:fileAtPath atomically:YES];
    }}
    

    【讨论】:

    • 所以如果文件存在就不写字符串?它不会检测和报告错误。更糟糕的是 OPs 代码。
    • 可以使用 [NSData writeToFile:options:error:] 代替...!
    • 是的,我知道。但是,我正在评论您的代码实际演示的内容。
    猜你喜欢
    • 2011-08-29
    • 1970-01-01
    • 1970-01-01
    • 2013-04-18
    • 2018-03-24
    • 2013-12-20
    • 1970-01-01
    • 1970-01-01
    • 2017-04-01
    相关资源
    最近更新 更多