简体   繁体   English

使用NSFetchedResultsController更新CoreData对象

[英]Update CoreData Objects with NSFetchedResultsController

I made an app which uses Core Data and fetched results controller. 我制作了一个使用核心数据和获取结果控制器的应用。

I can add CoreData objects and also delete them. 我可以添加CoreData对象,也可以删除它们。 Now I want to update an CoreData object via fetched results controller. 现在,我想通过获取的结果控制器更新CoreData对象。 I know that I have to fetch the objects and then I can change it. 我知道我必须先获取对象,然后才能对其进行更改。 But because I'm still learning I don't know how to do this. 但是因为我还在学习,所以我不知道该怎么做。 Now I'd like to ask you how to do this? 现在,我想问你怎么做?

When you fetch from CoreData, if you modify the results it will update the actual value within CoreData when you save it. 从CoreData获取数据时,如果修改结果,则保存时它将更新CoreData中的实际值。

You'll want to first perform your fetch: 您首先要执行提取:

NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@"Entity" inManagedObejctContext:moc]];
NSError *error = nil;
NSArray *results = [moc executeFetchRequest:request error:&error];

// error handling code

Once you have your results, you can modify the individual records... 获得结果后,您可以修改单个记录...

MyEntity *entity = [results objectAtIndex:0];
entity.title = @"updated attribute";
// save context
[moc save:&error];

EDIT: In swift, it will be something along the lines of the following: 编辑:很快,它将遵循以下内容:

let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
var moc = appDelegate.managedObjectContext!

var fetchRequest = NSFetchRequest()
fetchRequest.entity = NSEntityDescription.entityForName("Entity", inManagedObjectContext: moc)

var error: NSError?
var results = moc.executeFetchRequest(fetchRequest, error: &error)

// error handling code

var entity: MyEntity = MyEntity()
entity.title = "updated attribute"

moc.save(&error)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM