Core data not saving my data

前端 未结 2 499
名媛妹妹
名媛妹妹 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 :)

提交回复
热议问题