如何更新 Core Data 中的现有对象? [英] How to update existing object in Core Data?

查看:56
本文介绍了如何更新 Core Data 中的现有对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我插入新对象时,我使用以下代码:

When I insert new object I do with following code:

NSManagedObjectContext *context = [appDelegate managedObjectContext];

Favorits *favorits = [NSEntityDescription insertNewObjectForEntityForName:@"Favorits" inManagedObjectContext:context];

favorits.title = @"Some title";

NSError *error;                    
if (![context save:&error]) {
    NSLog(@"Whoops");
}

如何更新核心数据中的现有对象?

How can I update existing object in core data?

推荐答案

更新就像创建一个新的一样简单.

Updating is simple as creating a new one.

要更新特定对象,您需要设置 NSFetchRequest.此类相当于 SQL 语言中的 SELECT 语句.

To update a specific object you need to set up a NSFetchRequest. This class is equivalent to a SELECT statetement in SQL language.

这里有一个简单的例子:

Here a simple example:

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

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

// error handling code

数组 results 包含 sqlite 文件中包含的所有托管对象.如果要获取特定对象(或更多对象),则需要对该请求使用谓词.例如:

The array results contains all the managed objects contained within the sqlite file. If you want to grab a specific object (or more objects) you need to use a predicate with that request. For example:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"title == %@", @"Some Title"];
[request setPredicate:predicate]; 

在这种情况下,results 包含标题等于 Some Title 的对象.设置谓词就等于将 WHERE 子句放在 SQL 语句中.

In this case results contains the objects where title is equal to Some Title. Setting a predicate is equal to put the WHERE clause in a SQL statement.

有关更多信息,我建议您阅读 Core Data 编程指南和 NSFecthRequest 类参考.

For further info I suggest you to read the Core Data programming guide and NSFecthRequest class reference.

NSFecthRequest 类参考

希望有帮助.

EDIT(可用于更新的代码段)

EDIT (snippet that can be used to update)

// maybe some check before, to be sure results is not empty
Favorits* favoritsGrabbed = [results objectAtIndex:0];    
favoritsGrabbed.title = @"My Title";

// save here the context

或者如果您没有使用 NSManagedObject 子类.

or if you are not using a NSManagedObject subclass.

// maybe some check before, to be sure results is not empty
NSManagedObject* favoritsGrabbed = [results objectAtIndex:0];
[favoritsGrabbed setValue:@"My title" forKey:@"title"];

// save here the context

在这两种情况下,如果您对上下文执行 save,数据将被更新.

In both cases if you do a save on the context, data will be updated.

这篇关于如何更新 Core Data 中的现有对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆