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:
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.
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.
You have two options for maintaining you store with no duplicates:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With