2011-09-15 21 views
3

我想只在iPhone中的核心數據中插入那些不在sqllite表中的記錄。換句話說,我想在我的核心數據表中插入不同的記錄。我的插入代碼是如何在iPhone中通過核心數據插入不同記錄?

for(NSInteger j=0;j<[items count];j++){ 
      Story *story=(Story *)[NSEntityDescription insertNewObjectForEntityForName:@"Story" inManagedObjectContext:managedObjectContext]; 

      [story setTitle:[[items objectAtIndex:j] objectForKey:@"title"]]; 
      [story setDate:[[items objectAtIndex:j] objectForKey:@"date"]]; 
    } 

告訴我在這裏只插入不同記錄的方式。

回答

5

看看this page,「實現高效查找或創建」一節提供了有關如何實現更新/插入機制的詳細信息。

3

一種解決方案可能是爲您的實體指定一個index屬性(只是一個整數值),並在添加新實體之前檢查此屬性。

或者,如果您不希望重複成爲可能,您可以簡單地使用相同的titledate對故事執行取回。如果沒有從這個提取返回,那麼添加新的對象,如你自己的代碼。你可以這樣實現它:

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]; 

我發現來實現,它包含的通用方法來執行這些抓取工具類是非常有用的,因此,所有你需要做的就是告訴它你的實體的名稱,密鑰的字典&要檢查的值以及要搜索的上下文。保存重寫很多代碼!

希望這會有所幫助。