writeToFile:atomically只能第一次使用

时间:2011-07-25 19:30:28

标签: objective-c ios nsmutablearray writetofile

当我的应用程序启动时,查看是否存在plist,如果不存在则创建它。

NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"history.plist"];
    success = [fileManager fileExistsAtPath:filePath];
    if (success) {
        NSArray *arr = [[NSArray alloc] initWithContentsOfFile:[documentsDirectory stringByAppendingPathComponent:@"history.plist"]];
        for (NSDictionary *par in arr) {
            [self.history addObject:[[Paradero alloc] initWithDictionary:par]];
        }
    } else {
        [fileManager createFileAtPath:filePath contents:nil attributes:nil];
    }

现在,当用户关闭应用程序时,为了提供持久性,我将数据保存到该文件

- (void)applicationDidEnterBackground:(UIApplication *)application {
    /*
     Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
     If your application supports background execution, called instead of applicationWillTerminate: when the user quits.
     */
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"history.plist"];
    NSLog(@"%@", filePath);
    NSMutableArray *temparray = [[NSMutableArray alloc] initWithCapacity:5];
    for (Paradero *parada in self.history) {
        [temparray addObject:[parada asDictionary]];
    }
    NSLog(@"%@", temparray);
    NSLog(@"%c",[temparray writeToFile:filePath atomically:NO]);

    NSLog(@"yei");
}

使用NSString,NSArrays将对象转换为Dictionary,以便将其保存到文件中。这是第一次发生,这意味着,文件已经创建,没有任何内容,它工作正常,但是什么时候保存新数据,它失败了,没有给出理由。

1 个答案:

答案 0 :(得分:4)

解决。 作为记录: 第一个问题是我在iOS5模拟器上测试,好吧,我还不知道如何解决它。

真正的问题是因为周围有一些NSNull,所以,我只需将它们变成空字符串。

请记住检查NSNulls,如果他们来自网络服务,他们真的很痛苦。