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

查看:104
本文介绍了如何更新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

这里有一个简单的例子:

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 title等于某些标题。设置谓词等于在SQL语句中放置WHERE子句。

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.

有关更多信息,我建议您阅读核心数据编程指南和 NSFecthRequest 类参考。

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

NSFecthRequest类别参考

希望它有帮助。

EDIT (可用于更新)

// 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 子类。

// 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天全站免登陆