处理核心数据中的重复条目 [英] Handling duplicate entries in Core Data
问题描述
我有一个允许用户保存收藏夹的应用程序.我正在使用Core Data将收藏夹存储为托管对象.我已经编写了一些代码来防止存储重复项的可能性,但是我想知道是否有更好的方法来存储重复项.每个收藏夹对象都有一个唯一的ID字段.在下面的代码中,我只是循环遍历并检查ID字段,如果该值已经存在,请将标志值设置为true,然后退出循环.
I have an app that allows users to save favorites. I am using Core Data to store the favorites as managed objects. I have written some code to prevent the possibility of storing duplicates, but am wondering if there is a better way to do so. Each favorite object has an ID field that is unique. In the following code I am simply looping through and checking the ID field, and if the value already exists, setting a flag value to true, and breaking out of the loop.
-(BOOL)addFavorite{
BOOL entityExists = NO;
if(context){
// does this favorite already exist?
NSArray *allFaves = [AppDataAccess getAllFavorites];
for(Favorite *f in allFaves){
if([f.stationIdentifier isEqualToString:stID]){
entityExists = YES;
break;
}
}
if(!entityExists){
NSError *err = nil;
Favorite *fave = [Favorite insertInManagedObjectContext:context];
fave.stationRealName = riverGauge.name;
fave.stationIdentifier = stID;
fave.stationState = @"WV";
if(![context save:&err]){
NSLog(@"ERROR: Could not save context--%@", err);
}
return YES;
}
return NO;
}
我想知道Core Data是否能够检查要添加的对象是否重复.有谓词可以处理重复项检查吗?谢谢!
I was wondering if Core Data has the ability to check to see if an object being added is a duplicate. Is there a predicate that can handle checking for duplicates? Thanks!
推荐答案
CoreData本身不会唯一.它没有两个条目相同的概念.
CoreData does no uniquing by itself. It has no notion of two entries being identical.
要启用这种行为,您必须自己执行插入前搜索"或创建前提取"来自己实现.
To enable such a behavior you have to implement it yourself by doing a 'search before insert' aka a 'fetch before create'.
NSFetchRequest *fetch = [NSFetchRequest fetchRequestWithEntityName:@"Favorite"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"stationIdentifier == %@", stID];
[fetch setPredicate:predicate];
YourObject *obj = [ctx executeRequest:fetch];
if(!obj) {
//not there so create it and save
obj = [ctx insertNewManagedObjectForEntity:@"Favorite"]; //typed inline, dont know actual method
obj.stationIdentifier = stID;
[ctx save];
}
//use obj... e.g.
NSLog(@"%@", obj.stationIdentifier);
这篇关于处理核心数据中的重复条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!