Core data not saving my data

前端 未结 2 498
名媛妹妹
名媛妹妹 2021-01-20 21:45

I\'m using core data to save some integer (rate) and then I call save in the context:

HeartRateBeat * beat = [HeartRateBeat heartRateWithHeartRate:rate
              


        
相关标签:
2条回答
  • 2021-01-20 22:25

    I don't know about you guys, but when I want my Core Data to save, my Core Data better save.

    Here's some code that will for sure save all of your Core Datas.

    -(void)forceSave {
            NSManagedObjectContext * context = self.managedObjectContext; //Get your context here. 
        if (!context) {
            NSLog(@"NO CONTEXT!");
            return;
        }
    
        NSError * error;
        BOOL success = [context save:&error];
        if (error || !success) {
            NSLog(@"success: %@ - error: %@", success ? @"true" : @"false", error);
        }
    
        [context performSelectorOnMainThread:@selector(save:) withObject:nil waitUntilDone:YES];
        [context performSelector:@selector(save:) withObject:nil afterDelay:1.0];
        [context setStalenessInterval:6.0];
        while (context) {
            [context performBlock:^(){
                NSError * error;
                bool success =  [context save:&error];
                if (error || !success)
                    NSLog(@"success: %@ - error: %@", success ? @"true" : @"false", error);
    
            }];
            context = context.parentContext;
        }
    
        NSLog(@"successful save!");
    
    }
    

    Note that this is BAD CODE. Among other problems, it's not thread-safe and takes too long. However, try using this and deleting some parts of it to your satisfaction :)

    0 讨论(0)
  • 2021-01-20 22:28

    I get the same problem but I think its just because, I assume, like me you are just stopping the app through xcode and not actually closing it down. I use this code to force a write. Im using a UIManagedDocument, shared through appdelegate, rather than setting everything up manually.

    NSError *error = nil;
    
    if (![self.managedObjectContext save:&error]) {
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    
    [[AppDelegate sharedAppDelegate].userDatabase saveToURL:[AppDelegate sharedAppDelegate].userDatabase.fileURL forSaveOperation:UIDocumentSaveForOverwriting completionHandler:nil];
    
    0 讨论(0)
提交回复
热议问题