我有一个数组friendsArray
的字典对象,看起来像这样:
(
{
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 Browser
的屏幕截图
它存储数据但是复制了这本字典,我不知道为什么。
答案 0 :(得分: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
语句移到循环之外。