0

尝试更新一些核心数据。数据实际上是在“某处”更新,但它没有保存/更新数据库。

- (IBAction)Update:(id)sender {


    NSEntityDescription *entityDesc =
    [NSEntityDescription entityForName:@"Preferences"
                inManagedObjectContext:context];

    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:entityDesc];


    NSError *error;
    NSArray *objects = [context executeFetchRequest:request
                                              error:&error];

    if ([objects count] == 0) {
        // No update, didnt find any entries.

    } else {

        for (NSManagedObject *obj in objects) {           

            [obj setValue:_salesPrice.text forKey:@"value"];
            if(![context save:&error]){
                NSLog(@"Saving changes failed: %@", error);
            }

        }

    }
    //[context save:&error];
}

我已经[context save:&error];在评论区尝试过,但仍然没有保存。保存时我也没有错误。

4

1 回答 1

0

你只用 1 NSManagedObjectContext?您的命名约定并不理想。通常你会命名实体 Preference,因为它是一个对象。试试下面的代码。

CoreDataAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
// This is for completion. Usually you should not get the context from the App Delegate.   
// Its better to pass it from the App Delegate to 
// the initial view controller via a property (dependency injection).

NSFetchRequest *req = [[NSFetchRequest alloc] initWithEntityName:NSStringFromClass([Preferences class])];
    NSError *error = nil;
    NSArray *preferences = [context executeFetchRequest:req error:&error];

// Check error

if ([preferences count] == 0) {
    // No update, didnt find any entries.
} else {
    for (Preferences *preference in preferences) {           
        [preference setValue:_salesPrice.text forKey:@"value"];
    }
}
[context save:&error];
// Check error
于 2013-01-04T18:04:28.697 回答