从字典的数组中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浏览器的屏幕截图
它是存储数据,但复制这本字典,我不知道为什么。
答
试试下面的 - 它有点清洁:)
观察日志语句多少次输出,并检查它的输出对象。
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
声明外循环。
你不只是运行该代码不止一次吗?尝试清除所有数据 - 重置模拟器,然后运行一次。 – Rich
我试过:)它一直重复着。我知道我做错了什么,只是无法弄清楚什么。 – April
添加日志,出于某种原因您正在运行两次。 – Wain