2012-04-22 119 views
7

我对Core Data编程非常新颖。我有一个问题,我希望得到一些澄清。如何检查一个实体是否已经存在于永久存储中

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

  • 的companyName
  • companyEmail
  • companyPhoneNo
  • companyUserName
  • companyPassword

在这对象companyName属性被索引。

所以,我的问题是,我怎样才能确保只有条目具有相同的companyName,companyEmail,companyPhoneNo,companyUserName和companyPassword?

我是否需要提出检查是否有任何具有相同属性值的记录,或者是否使用对象ID进行简单检查?

谢谢。

回答

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你之前设置的实体。

相关问题