在插入之前检查 sqlite 中的重复项(核心数据)
我正在通过核心数据将新对象插入数据库。 在插入值之前,有什么方法可以检查数据库中是否有重复项?
for (int i =0;i<[categoryArray count];i++)
{
Category * cat = [categoryArray objectAtIndex:i];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"ICategory" inManagedObjectContext:managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entity];
ICategory *catt = (ICategory *)[NSEntityDescription insertNewObjectForEntityForName:@"ICategory" inManagedObjectContext:managedObjectContext];
[catt setName:cat.name];
[catt setID:cat.ID];
[catt setPhoto:cat.photo];
[catt setSapphireID:event.ID];
NSLog(@"cattttt have %@", catt);
}
每次我运行该应用程序时,它都会再次重新插入值。我想检查其中是否有任何新类别,如果没有,那么我将仅添加该新类别。
i'm inserting new objects into the database by core data.
Is there any way to check if there is any duplicate in the database before i insert the values in?
for (int i =0;i<[categoryArray count];i++)
{
Category * cat = [categoryArray objectAtIndex:i];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"ICategory" inManagedObjectContext:managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entity];
ICategory *catt = (ICategory *)[NSEntityDescription insertNewObjectForEntityForName:@"ICategory" inManagedObjectContext:managedObjectContext];
[catt setName:cat.name];
[catt setID:cat.ID];
[catt setPhoto:cat.photo];
[catt setSapphireID:event.ID];
NSLog(@"cattttt have %@", catt);
}
everytime i run the app , it reinsert the values again. i want to check if there is any new category in it if there isnt then i will add that new one in only.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
没有办法免费检查重复项。您需要手动处理用于确定两个对象相同的谓词。
最简单的是使用
-[NSMangedObjectContext countForFetchRequest:error:]
快速查看对象是否已经存在,因为计数大于 0。遵循三个规则(一般为第三个)当你需要重写它时) 我为自己做了一些方便的方法来处理这个问题。更具体地说,
-[NSManagedObjectContext insertNewUniqueObjectForEntityForName:withPredicate:]
。如果您想使用它,可以在 https://github.com/jayway/CWCoreData 获取它的开源版本作为灵感,或按原样。There is no way to check for duplicates for free. You need to manually handle the predicate you use for determining that two objects are the same.
Easiest is to use
-[NSMangedObjectContext countForFetchRequest:error:]
quickly see if the object already exists, as in the count is greater than 0.Following the rule of three (make it general the third time you need to rewrite it) I have made some convenience methods for myself to handle this. More specifically
-[NSManagedObjectContext insertNewUniqueObjectForEntityForName:withPredicate:]
. It's available as open source at https://github.com/jayway/CWCoreData if you want to use it as inspiration, or as-is.