从字典的数组中CoreData存储对象

问题描述:

我的字典对象的数组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

试试下面的 - 它有点清洁:)

观察日志语句多少次输出,并检查它的输出对象。

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