如何更新Objective-C中的coredata值

时间:2016-12-15 07:24:01

标签: ios objective-c core-data

我是iOS的新手,我遇到了关于更新coredata值的问题。

保存

 NSManagedObjectContext *context = [self managedObjectContext];
 NSManagedObject *device;

                if (self.device) {
                    // Update existing device
                    [device setValue:GlobalIndexPath forKey:@"key"];                                        
                } else {
                    // Create a new device
                    NSManagedObject *newDevice = [NSEntityDescription insertNewObjectForEntityForName:@"Device" inManagedObjectContext:context];
                    [newDevice setValue:GlobalIndexPath forKey:@"key"];
                }

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

我获取核心数据的代码是

NSManagedObjectContext *context = [self managedObjectContext];

NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@"EntityName" inManagedObjectContext:context]];

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

更新我并使用代码

NSManagedObject* favoritsGrabbed = [results objectAtIndex:0];
[favoritsGrabbed setValue:@"1" forKey:@"Key"];

更新代码不更新它添加一个对象。

注意 - GlobalIndexPath是字符串的名称。

但这对我没有任何建议。谢谢Advcance!

1 个答案:

答案 0 :(得分:2)

每次对任何NSManagedObject进行更改时都需要保存上下文,并希望它保持不变。试试这个:

NSManagedObject* favoritsGrabbed = [results objectAtIndex:0];
[favoritsGrabbed setValue:@"1" forKey:@"Key"];
NSError *error = nil;
// Save the object to persistent store
if (![context save:&error]) {
    NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
}