Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check whether an entity already exists in persistent store

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

Supposing I have an NSManagedObject called Company, with the following attributes:

  • companyName
  • companyEmail
  • companyPhoneNo
  • companyUserName
  • companyPassword

In this object the companyName attribute is indexed.

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

Do I need to make a request to check if there are any records with the same attribute values or is a simple check with the object id sufficient?

Thanks.

like image 929
prasad1250 Avatar asked Apr 22 '12 05:04

prasad1250


2 Answers

Here's an example may be helps:

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 fetch entity actually, it just returns a number of entities that match the predicate you set before.

like image 86
Kjuly Avatar answered Nov 27 '22 05:11

Kjuly


You have two options for maintaining you store with no duplicates:

  1. Make fetch in insert.
  2. Insert all the new data and then delete the duplicates before saving.

What is faster and more convenient? Presumably first way. But you'd better test it using Instruments and find the right way for your app.

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

like image 22
Nikita Pestrov Avatar answered Nov 27 '22 04:11

Nikita Pestrov