简体   繁体   中英

writeToFile:atomically only works first time

When my app starts, looks if a plist exists, if it doesn't it creates it.

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];
    }

Now, when the user closes the app, to provide persistance I save the data to that file

- (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");
}

The object is converted to a Dictionary with NSString, NSArrays so it can be saved to the file. The first time this ever happens, that means, the file was created, nothing on it, it works just fine, but when is time to save new data, it fails, no reason given.

Solved. For the record: The first issue was that i was testing on iOS5 Simulator, well, i don't know how to fix it there yet.

The real issue was because there was some NSNull around, so, I just needed to turn them into empty strings.

Remember to check for NSNulls, they are really a pain if they turn out from a web service.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM