一种解决方案可能是为您的实体提供一个index
属性(只是一个整数值),并在添加新实体之前检查这一点。
或者,如果您不希望重复,您可以简单地对具有相同title
and的故事执行提取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. 省去重写大量代码!
希望这可以帮助。