【问题标题】:Storing NSArray/NSMuatbleArray in File将 NSArray/NSMuatbleArray 存储在文件中
【发布时间】:2012-06-18 21:10:00
【问题描述】:

我开始在文件中存储一个 NSArray,但我一直收到 nil 作为响应...

Apple 文档说 nil 表示您的文件不存在,但我很确定我的文件存在(我可能没有正确构建路径)...

这是我用来将 NSArray 存储在文件中的代码...

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"scorecards" ofType:@"dgs"];

NSArray *myArray = [[NSArray alloc] initWithObjects:@"J", @"ANA", @"MY", @"GDON", nil];

[myArray writeToFile:filePath atomically:YES];

NSArray *mynewArray = [NSArray arrayWithContentsOfFile:filePath];

NSLog(@"%@", [mynewArray objectAtIndex:2]);

我还截取了 Xcode 的屏幕截图,向大家展示我的文件确实存在...

该文件清楚地保存在 ScorecardsSaved 组中,该文件名为 scorecards,扩展名为 dgs(这是我为我的具体应用 - Dot Golf Scorecard - dgs)

【问题讨论】:

    标签: iphone objective-c ios xcode ios5


    【解决方案1】:

    确实,您的文件路径使用pathForResource 方法,因此它将指向您的应用程序包中的一个位置,该位置不可写。

    相反,您必须写入设备/模拟器上的应用程序文档目录。

    NSURL *documentsDirectory = 
       [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory 
         inDomains:NSUserDomainMask] lastObject];
    NSURL *fileURL = [documentsDirectory 
       URLByAppendingPathComponent:@"storecards.dgs"];
    

    所以如果你的 bundle 版本的文档中包含一些种子数据,请先将其复制到 app 文档目录中。

    【讨论】:

    • 但我需要 filePath 是 NSstring 而不是 NSurl
    • NSString *path = [myURL path]; ;-)
    【解决方案2】:
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *filePath = [documentsDirectory stringByAppendingPathComponent:FILE_NAME];
    
    [myArray writeToFile:filePath atomically:YES];
    

    【讨论】:

      猜你喜欢
      • 2011-03-10
      • 1970-01-01
      • 2012-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多