我正在使用swift处理CoreData,在我的项目中我想在CoreData中存储/获取字典。我的词典包含类别详细信息以及子类别详细信息(在字典数组中)。我已经采用了类别详细信息的模型,但我没有得到如何存储特定类别的子类别详细信息。
我应该为子类别采用单独的模型吗?
所以请帮我这样做。
我的字典看起来像:
{
"category": [
{
"id": "1",
"category_name": "Water",
"sub_category_count": "3",
"sub_category": [
{
"sub_categoryid": "1",
"sub_categoryname": "Water1"
},
{
"sub_categoryid": "2" ,
"sub_categoryname": "Water2"
},
{
"sub_categoryid": "3" ,
"sub_categoryname": "Water3"
}
]
},
{
"id": "2",
"category_name": "Health",
"sub_category_count": "3",
"sub_category": [
{
"sub_categoryid": "1" ,
"sub_categoryname": "Health1"
},
{
"sub_categoryid": "2" ,
"sub_categoryname": "Health2"
},
{
"sub_categoryid": "3" ,
"sub_categoryname": "Health3"
}
]
}
]
}
答案 0 :(得分:1)
您应该为子类别创建单独的实体,并为子类别添加一对多关系。
然后转到编辑器>创建NSManagedObject子类。 您将获得4个文件
SubCategory.swift
SubCategory+CoreDataProperties.swift
Category.swift
Category+CoreDataProperties.swift
在Category.swift
中添加以下方法
func addSubcategoryObject(sub: SubCategory) {
sub.category = self
}
然后解析您的数据,如下所示
data = your data.....
let json = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) as! NSDictionary
if let categories = json["category"] as? [NSDictionary] {
for category in categories {
let categoryObject = NSEntityDescription.insertNewObjectForEntityForName("Category", inManagedObjectContext: self.managedObjectContext) as! Category
categoryObject.category_name = category["category_name"] as? String
categoryObject.id = NSNumber(integer: Int((category["id"] as? String)!)!)
categoryObject.sub_category_count = NSNumber(integer: Int((category["sub_category_count"] as? String)!)!)
if let subcateories = category["sub_category"] as? [NSDictionary] {
for subCategory in subcateories {
let subCategoryObject = NSEntityDescription.insertNewObjectForEntityForName("SubCategory", inManagedObjectContext: self.managedObjectContext) as! SubCategory
subCategoryObject.sub_categoryname = subCategory["sub_categoryname"] as? String
subCategoryObject.sub_categoryid = NSNumber(integer: Int((subCategory["sub_categoryid"] as? String)!)!)
categoryObject.addSubcategoryObject(subCategoryObject)
}
}
}
}
修改强>
您应该在Subcategory
中向Category