2014-02-18 36 views
2

我的字典對象的數組friendsArray這看起來是這樣的:從字典的數組中CoreData存儲對象

(
     { 
     name = "james p"; 
     phone = 345345345; 
    }, 
     { 
     name = "sam b"; 
     phone = 345345345; 
    }, 
     { 
     name = "aaron s"; 
     phone = 346346456; 
    } 
) 

現在我將它存儲到coredata這樣

NSMutableDictionary *friends = [[NSMutableDictionary alloc] init]; 

    for (int count = 0; count <[friendsArray count]; count++) { 
    NSError *error; 
    NSEntityDescription *entityDesc = [NSEntityDescription entityForName:@"FriendContacts" inManagedObjectContext:context]; 
    NSManagedObject *friendsObject = [[NSManagedObject alloc] initWithEntity:entityDesc insertIntoManagedObjectContext:context]; 

    NSFetchRequest *request   = [[NSFetchRequest alloc] init]; 
    [request setEntity:entityDesc]; 

    friends = [friendsArray objectAtIndex:count]; 
    [friendsObject setValue:[friends objectForKey:@"name"] forKey:@"name"]; 
    [friendsObject setValue:[friends objectForKey:@"phone"] forKey:@"phone"]; 
    [context save:&error]; 

} 

這裏是SQL瀏覽器的屏幕截圖

它是存儲數據,但複製這本字典,我不知道爲什麼。

+0

你不只是運行該代碼不止一次嗎?嘗試清除所有數據 - 重置模擬器,然後運行一次。 – Rich

+0

我試過:)它一直重複着。我知道我做錯了什麼,只是無法弄清楚什麼。 – April

+0

添加日誌,出於某種原因您正在運行兩次。 – Wain

回答

2

試試下面的 - 它有點清潔:)

觀察日誌語句多少次輸出,並檢查它的輸出對象。

NSEntityDescription *entityDesc = [NSEntityDescription entityForName:@"FriendContacts" inManagedObjectContext:context]; 
for (NSDictionary *friend in friendsArray) { 

    NSManagedObject *friendsObject = [[NSManagedObject alloc] initWithEntity:entityDesc insertIntoManagedObjectContext:context]; 

    [friendsObject setValue:[friend objectForKey:@"name"] forKey:@"name"]; 
    [friendsObject setValue:[friend objectForKey:@"phone"] forKey:@"phone"]; 

    NSLog(@"Created new friends object: %@", friendsObject); 

    if ([context hasChanges]) { 
     NSError *error; 
     if (![context save:&error]) { 
      NSLog(@"Problem saving changes: %@", error); 
     } 
    } 
} 

編輯:

您也可能會更好循環結束後太(如果你有一個大的數據集)後保存,只需移動if聲明外循環。

+0

它不應該如此。看到這個:http://i.imgur.com/xlCLY3s.png – April

+0

OMG我調用了同樣的方法兩次。多麼愚蠢。對不起,打擾你們..是的,我用快速枚舉之前,但後來我切換到傳統的循環檢查什麼是錯的,我做了哈哈..感謝:) – April

+0

@ user3049559其始終的方式。儘管如此,如果你有很多對象,你最好在循環後保存。我已經添加了關於此的編輯。 – Rich