我有一个NSDictionary和一个CoreData数据库。我想将NSDictionary插入数据库。
我该怎么做(如果可能的话,代码片段)?
字典属性的合适类型是什么?
答案 0 :(得分:27)
您需要将NSDictionary序列化为NSData,CoreData可以保存为NSData 但是你将无法搜索NSDictionary的(谓词)元素。
如果我们考虑一下,NSDictionary就是一个数据集合 数据库中的表是一种数据集合 在CoreData中,最接近数据集合的是NSManagedObject。
所以我的建议是创建一个NSManagedObject子类,它将保存您在NSDictionary中的信息。 key
将是属性,值将是该属性的value
。并且您将能够基于该NSManagedObject子类的属性进行搜索。
答案 1 :(得分:8)
我找到了另一种通过创建数据类型为'Transformable'的属性将Dictionary添加到Coredata的方法。
例如,在项目中创建一个实体&数据类型为Transformable的属性。 为NSManagedObject生成子类。属性将以数据类型“id”提供,转换为NSDictionary。
下面是我做的(我的NSManagedObject子类名是'DictTest')
-(void)InsertIntoDataBase
{
DictTest *entityDict=(DictTest*)[NSEntityDescription insertNewObjectForEntityForName:@"DictTest" inManagedObjectContext:self.managedObjectContext];
NSMutableDictionary *mutDict=[NSMutableDictionary dictionary];
[mutDict setValue:@"1" forKey:@"1"];
[mutDict setValue:@"2" forKey:@"2"];
[mutDict setValue:@"3" forKey:@"3"];
[mutDict setValue:@"4" forKey:@"4"];
[mutDict setValue:@"5" forKey:@"5"];
[mutDict setValue:@"6" forKey:@"6"];
[mutDict setValue:@"7" forKey:@"7"];
[mutDict setValue:@"8" forKey:@"8"];
[mutDict setValue:@"9" forKey:@"9"];
[mutDict setValue:@"10" forKey:@"10"];
[entityDict setInfoDict:mutDict];
NSError *error;
if(![self.managedObjectContext save:&error])
{
NSLog(@"error description is : %@",error.localizedDescription);
}
else{
NSLog(@"Saved");
}
}
获取记录
-(void)FetchRecord
{
NSFetchRequest *request=[[NSFetchRequest alloc]init];
NSEntityDescription *entity=[NSEntityDescription entityForName:@"DictTest" inManagedObjectContext:self.managedObjectContext];
[request setEntity:entity];
NSArray *fetchArray= [self.managedObjectContext executeFetchRequest:request error:nil];
for (DictTest *obj in fetchArray) {
NSLog(@"Dict is : %@",obj.infoDict);
}
}
答案 2 :(得分:5)
设置实体描述,插入新对象,然后使用:
[managedObject setValuesForKeysWithDictionary:dict];
答案 3 :(得分:4)
为什么不直接使用NSDictionary中的所有数据创建一个实体,然后只需解析它。
检查this out for some CoreData code snippets.您只需创建一些实体即可存储词典信息。然后,您可以解析字典并保存适当的属性:
NSManagedObject *photoObject = [NSEntityDescription insertNewObjectForEntityForName:@"Photo"
inManagedObjectContext:context];
[photoObject setPhotographer:[myDictionary objectForKey:@"photographer"]];
and so on...
无论您的XML数据结构有多复杂,如果您可以设置一个漂亮的实体结构,在CoreData中简单地将它全部简单化相当容易。如果您花时间创建实体而不是仅仅将整个字典转储到单个字段中,那么查询也会更容易。