1つの解決策は、エンティティにindex
属性(整数値のみ)を指定し、新しいエンティティを追加する前にこれを確認することです。
または、重複を可能にしたくない場合は、同じtitle
と。を使用してストーリーに対してフェッチを実行するだけdate
です。このフェッチから何も返されない場合は、独自のコードのように新しいオブジェクトを追加します。次のように実装できます。
NSString *title = [[items objectAtIndex:i] objectForKey:@"title"];
NSDate *date = [[items objectAtIndex:i] objectForKey:@"date"];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Story" inManagedObjectContext:managedObjectContext];
// Create the predicates to check for that title & date.
NSString *predTitleString = [NSString stringWithFormat:@"%@ == %%@", @"title"];
NSString *predDateString = [NSString stringWithFormat:@"%@ == %%@", @"date"];
NSPredicate *predTitle = [NSPredicate predicateWithFormat:predTitleString, @"title"];
NSPredicate *predDate = [NSPredicate predicateWithFormat:predDateString, @date];
NSArray *predArray = [NSArray arrayWithObjects:predTitle, predDate, nil];
NSPredicate *predicate = [NSCompoundPredicate andPredicateWithSubpredicates:predArray];
// Create the fetch request.
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setEntity:entity];
[fetchRequest setPredicate:predicate];
// Fetch results.
NSError *error = nil;
NSArray *array = [context executeFetchRequest:fetchRequest error:&error];
// If no objects returned, a story with this title & date does not yet exist in the model, so add it.
if ([array count] == 0) {
Story *story=(Story *)[NSEntityDescription insertNewObjectForEntityForName:@"Story" inManagedObjectContext:managedObjectContext];
[story setTitle:title];
[story setDate:date];
}
[fetchRequest release];
これらのフェッチを実行するためのジェネリックメソッドを含むユーティリティクラスを実装すると非常に便利であることがわかったので、エンティティの名前、チェックするキーと値のディクショナリ、および検索するコンテキストを指定するだけです。 in。多くのコードを書き直す手間が省けます!
お役に立てれば。