简体   繁体   中英

Core data won't save correctly

I'm using a data model called settings which I setup in didLoad of my viewController:

settings = [NSEntityDescription insertNewObjectForEntityForName:@"Settings" inManagedObjectContext:[self managedObjectContext]];

Heres the managedobjectContext method:

- (NSManagedObjectContext *)managedObjectContext {
NSManagedObjectContext *context = nil;
id delegate = [[UIApplication sharedApplication] delegate];
if ([delegate performSelector:@selector(managedObjectContext)]) {
    context = [delegate managedObjectContext];
}
return context;
}

When my stepper increments I want to update a string and then update the db.

- (IBAction)RowStepperAction:(UIStepper *)sender
{
    double value = [sender value];
    settings.numberofrows = [NSNumber numberWithDouble:value];
    [self.RowNumber setText:[NSString stringWithFormat:@"%d", (int)value]];

    NSError *error = nil;
    // Save the object to persistent store
    if (![[self managedObjectContext] save:&error]) {
        NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
    }
}

When I come to load the view again I do:

[self.ColumnStepper setValue:[settings.numberofcolumns doubleValue]];
[self.RowStepper setValue:[settings.numberofrows doubleValue]];

This returns the default values I set in the database. Why is this?

Every time you load the view again, you're creating a brand new settings object :

settings = [NSEntityDescription insertNewObjectForEntityForName:@"Settings" inManagedObjectContext:[self managedObjectContext]];

This will have your default values. You need instead to fetch your existing settings object, and only create a new one if that doesn't exist.

Your database will currently have several settings objects, one for each time you've loaded the view.

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