如何检查实体是否已存在于持久性存储中

时间:2012-04-22 05:33:37

标签: objective-c core-data

我是Core Data编程的新手。我有一个问题,我希望得到一些澄清。

假设我有一个名为Company的NSManagedObject,具有以下属性:

  • 的companyName
  • companyEmail
  • companyPhoneNo
  • companyUserName
  • companyPassword

在此对象中,companyName属性已编制​​索引。

所以,我的问题是,如何确保只有相同的companyName,companyEmail,companyPhoneNo,companyUserName和companyPassword的条目?

我是否需要发出请求以检查是否有任何具有相同属性值的记录,或者只是对象ID足够的简单检查?

感谢。

2 个答案:

答案 0 :(得分:13)

这里有一个例子可能有帮助:

NSError * error;
NSFetchRequest * fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setEntity:[NSEntityDescription entityForName:NSStringFromClass([self class])
                                    inManagedObjectContext:managedObjectContext]];
[fetchRequest setFetchLimit:1];

// check whether the entity exists or not
// set predicate as you want, here just use |companyName| as an example
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"companyName == %@", companyName]];

// if get a entity, that means exists, so fetch it.
if ([managedObjectContext countForFetchRequest:fetchRequest error:&error])
  entity = [[managedObjectContext executeFetchRequest:fetchRequest error:&error] lastObject];
// if not exists, just insert a new entity
else entity = [NSEntityDescription insertNewObjectForEntityForName:NSStringFromClass([self class])
                                            inManagedObjectContext:managedObjectContext];
[fetchRequest release];

// No matter it is new or not, just update data for |entity|
entity.companyName = companyName;
// ...

// save
if (! [managedObjectContext save:&error])
  NSLog(@"Couldn't save data to %@", NSStringFromClass([self class]));

提示:countForFetchRequest:error:实际上不会获取实体,它只会返回一些与您之前设置的predicate匹配的实体。

答案 1 :(得分:1)

您可以使用两种选项来维护存储而不会重复:

  1. 在插入中进行提取。
  2. 插入所有新数据,然后在保存之前删除重复项。
  3. 什么是更快更方便?大概是第一种方式。但是你最好使用Instruments测试它,找到适合你应用的正确方法。

    以下是此问题的文档。 http://developer.apple.com/library/mac/ipad/#documentation/Cocoa/Conceptual/CoreData/Articles/cdImporting.html#//apple_ref/doc/uid/TP40003174-SW1

相关问题