一種解決方案可能是爲您的實體指定一個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];
我發現來實現,它包含的通用方法來執行這些抓取工具類是非常有用的,因此,所有你需要做的就是告訴它你的實體的名稱,密鑰的字典&要檢查的值以及要搜索的上下文。保存重寫很多代碼!
希望這會有所幫助。