役立つ例を次に示します。
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
。以前に設定したエンティティと一致するエンティティの数を返すだけです。