将 NSDictionary 插入 CoreData
我有一个 NSDictionary 和一个 CoreData 数据库。我想将 NSDictionary 插入数据库。
我该如何做到这一点(如果可能的话,请提供代码片段)?
字典的属性适合什么类型?
I have an NSDictionary and a CoreData Database. I want to insert the NSDictionary into the database.
How can I do this (code snippets if possible)?
What is the suitable type for the attribute of the dictionary ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您需要将 NSDictionary 序列化为 NSData,CoreData 可以保存 NSData。
但是您将无法搜索 NSDictionary 的(谓词)元素。
如果我们考虑一下这一点,NSDictionary 就是一个数据集合。
数据库中的表是一种数据集合。
在 CoreData 中,最接近数据集合的是 NSManagedObject。
所以我的建议是创建一个 NSManagedObject 子类来保存 NSDictionary 中的信息。
key
将是属性,值将是该属性的value
。您将能够根据该 NSManagedObject 子类的属性进行搜索。You would need to serialize your NSDictionary to an NSData, CoreData can hold to NSData.
But you won't be able to search (predicate) element of your NSDictionary.
And if we think about this, NSDictionary is a collection of data.
A Table in a database is kind of a collection of data.
In CoreData the closest thing you got to a collection of data is NSManagedObject.
So my advice would be to make a NSManagedObject subclass that would hold the information you have in your NSDictionary. The
key
would be the attribute and the value would be thevalue
of that attribute. And you would be able to search based on the attribute of that NSManagedObject subclass.我找到了另一种通过创建数据类型为“Transformable”的属性将字典添加到 Coredata 中的方法。
例如,在您的项目中创建一个实体&数据类型为 Transformable 的属性。
生成 NSManagedObject 的子类。属性将可用数据类型“id”,更改为 NSDictionary。
所做的事情(我的 NSManagedObject 子类名称是“DictTest”)
下面是我为获取记录
I found another way to add Dictionary into Coredata by creating an attribute with data type 'Transformable'.
For example create an entity in your project & attribute with data type Transformable.
Generate subclass for NSManagedObject. Attribute will be available with data type 'id', change into NSDictionary.
Below is what I did (My NSManagedObject sub class name is 'DictTest')
for Fetching records
设置实体描述,插入新对象,然后使用:
Set up your entity description, insert a new object, then use:
为什么不使用 NSDictionary 中的所有数据创建一个实体,然后对其进行解析。
检查这个获取一些 CoreData 代码片段。 您可以简单地创建一些实体来存储字典的信息。然后,您可以解析字典并保存正确的属性:
无论您的 XML 数据结构多么复杂,如果您可以设置一个很好的实体结构,那么在 CoreData 中将其全部简化是相当容易的。如果您花时间创建实体而不是仅仅将整个字典转储到单个字段中,那么您还会更轻松地进行查询。
Why don't you just create an entity with all the data from your NSDictionary and then just parse through it.
Check this out for some CoreData code snippets. You can simply create a few entities to store the info of your dictionaries. You can then parse through your dictionary and save the proper attributes:
No matter how complex you XML data structure, if you can set up a nice entity structure, it is fairly easy to simply dumb it all in CoreData. You'll also have a much easier time with queries if you take the time to create entities instead of just dumping the whole dictionary in a single field.