How to check if an entity exists in persistent storage

I am very new to programming Core Data. I have a question that I hope to get some clarification on.

Suppose I have an NSManagedObject named Company with the following attributes:

  • COMPANYNAME
  • companyEmail
  • companyPhoneNo
  • companyUserName
  • companyPassword

The companyName attribute is indexed in this object.

So my question is: how can I make sure that there will only be an entry with the same company name, companyEmail, companyPhoneNo, companyUserName and companyPassword?

I need to make a request to check if there are records with the same attribute values ​​or a simple check with a sufficient object identifier?

Thanks.

+7
source share
2 answers

Here is an example that might help:

 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])); 

Tip: countForFetchRequest:error: does not actually retrieve the entity, it simply returns the number of objects that match the predicate you specified earlier.

+13
source

You have two options for saving your storage without duplicates:

  • Make insert fetch.
  • Insert all new data and then delete duplicates before saving.

Which is faster and more convenient? Presumably the first way. But it’s better to check it with the tools and find the right way for your application.

Here are the documents on this. http://developer.apple.com/library/mac/ipad/#documentation/Cocoa/Conceptual/CoreData/Articles/cdImporting.html#//apple_ref/doc/uid/TP40003174-SW1

+1
source

All Articles