在CoreData中存储和获取字典数组

时间:2015-11-18 05:39:47

标签: ios swift core-data

我正在使用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"
      }
     ]
   }
]
}

1 个答案:

答案 0 :(得分:1)

您应该为子类别创建单独的实体,并为子类别添加一对多关系。

托管对象模型将类似于enter image description here

然后转到编辑器>创建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

添加反向关系类别