ios 如何使用核心数据执行插入/更新
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4102460/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to Perform a Insert/Update With Core Data
提问by slevytam
I've got the basics of inserting records and deleting records with Core Data; however, I'd appreciate help with one of the most common functions - the insert/update.
我已经掌握了使用 Core Data 插入记录和删除记录的基础知识;但是,我很感激最常见的功能之一 - insert/update 的帮助。
Basically, I use NSMutableArray
arrayWithContentsOfURL
to get an array that contains rows from a mysql
table. What I need to do is now sync up my CoreData
store.
基本上,我NSMutableArray
arrayWithContentsOfURL
用来获取一个包含mysql
表中行的数组。我现在需要做的是同步我的CoreData
商店。
In other words, I need to add every row in the array to my CoreData
table but if it already exists I need to update the record with the latest values. Also if it exists in Core Data and not in the downloaded array, I'd need to delete it.
换句话说,我需要将数组中的每一行添加到我的CoreData
表中,但如果它已经存在,我需要用最新的值更新记录。此外,如果它存在于 Core Data 而不是下载的数组中,我需要将其删除。
I probably could hack this together; however, I'd like to see how its properly and efficiently done without memory leaks.
我可能可以一起破解它;但是,我想看看它是如何在没有内存泄漏的情况下正确有效地完成的。
回答by Andrew Natoli
There are two ways to insert data into Core Data - and whichever one you use is up to you. However, one of them depends on whether you have generated Model classes for your data model for the Core Data db.
有两种方法可以将数据插入到 Core Data 中——使用哪种方法取决于您。但是,其中之一取决于您是否为 Core Data db 的数据模型生成了模型类。
The regular way is to use the following:
常规方法是使用以下方法:
NSManagedObject *object = [NSEntityDescription insertNewObjectForEntityForName:@"table"
inManagedObjectContext:context];
[object setValue:@"value1" forKey:@"stringColumn"];
[object setValue:12 forKey:@"numberValue"];
NSError *error;
if (![context save:&error]) {
NSLog(@"Failed to save - error: %@", [error localizedDescription]);
}
This is assuming you've already got your managed object context set up. It is much more efficient if you create and insert your objects into the context in a loop, and then save after the loop ends.
这是假设您已经设置了托管对象上下文。如果您在循环中创建对象并将其插入上下文中,然后在循环结束后保存,则效率会更高。
The other method isn't much different, but is much safer in terms of type safety. If you have generated model classes (which you can do from the xcdatamodels) then you can simply create an object of that class and set its properties.
另一种方法没有太大不同,但在类型安全方面更安全。如果您已经生成了模型类(您可以从 xcdatamodels 中生成),那么您可以简单地创建该类的对象并设置其属性。
TableObject *object = [NSEntityDescription insertNewObjectForEntityForName:@"table"
inManagedObjectContext:context];
[object setStringColumn:@"value1"];
[object setNumberValue:12];
NSError *error;
if (![context save:&error]) {
NSLog(@"Failed to save - error: %@", [error localizedDescription]);
}
To delete from a table, simply retrieve the object from the table (I'm assuming you are using the second method here for insertions, and as such have generated model classes) and use the following:
要从表中删除,只需从表中检索对象(我假设您在此处使用第二种方法进行插入,因此已生成模型类)并使用以下内容:
[context deleteObject:object];
Note that you will need to call save for that to take effect as well.
请注意,您还需要调用 save 才能使其生效。
Hope this helps! Good luck!
希望这可以帮助!祝你好运!
EDIT: Sorry, I must've misread the question!
编辑:对不起,我一定是误读了这个问题!
To examine an existing record, you'll want to create a Fetch Request, and then execute it on your managed object context. At bare minimum, a Fetch Request requires an entity (so it knows what table to search on). To specify search terms, you will need to create a predicate (otherwise the request will simply return everything in the table). You can also specify a set of sort descriptors so that your results will be sorted.
要检查现有记录,您需要创建一个 Fetch 请求,然后在您的托管对象上下文中执行它。在最低限度,为获取请求需要一个实体(所以它知道什么表格要搜索的)。要指定搜索词,您需要创建一个谓词(否则请求将简单地返回表中的所有内容)。您还可以指定一组排序描述符,以便对结果进行排序。
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"table" inManagedObjectContext:context];
[request setEntity:entity];
NSError *errorFetch = nil;
NSArray *array = [context executeFetchRequest:request error:&errorFetch];
This code creates a fetch request, and returns every object from the table named "table" in an array. From here, since all of the required objects are in the array, you can inspect and edit the records. If you make any changes, remember to save the context! The following loop logs the first value in each object, using the same table as the above examples.
此代码创建一个获取请求,并以数组形式返回名为“table”的表中的每个对象。从这里开始,由于所有必需的对象都在数组中,您可以检查和编辑记录。如果您进行任何更改,请记住保存上下文!以下循环使用与上述示例相同的表记录每个对象中的第一个值。
for(TableObject *object in array)
{
NSLog(@"object value1 = %@", object.value1);
}
You can also delete records from this point as well using the above mentioned function.
您也可以使用上述功能从这一点删除记录。
For more information about Fetch Requests, please give the class referencea look. I would also highly recommend reading about sort descriptors and predicates, since they're very important for searching your Core Data db, and certain uses of them are less efficient than others (particularly in the creation of NSPredicates).
有关 Fetch Requests 的更多信息,请查看类参考。我还强烈建议阅读有关排序描述符和谓词的内容,因为它们对于搜索 Core Data 数据库非常重要,并且它们的某些用途比其他用途效率低(特别是在创建 NSPredicates 时)。
Good luck!
祝你好运!