Ios 我可以使用相同的上下文在coredata中保存两个实体吗?
我不知道我是否正确地描述了这个问题,但我的困惑是:现在我有一个类似这样的json`Ios 我可以使用相同的上下文在coredata中保存两个实体吗?,ios,json,swift,core-data,Ios,Json,Swift,Core Data,我不知道我是否正确地描述了这个问题,但我的困惑是:现在我有一个类似这样的json` [ { "title": "TextBook", "items" : [ { "name" : "firstBook", "instore" : true } ] }, { "title": "Charger",
[
{
"title": "TextBook",
"items" : [
{
"name" : "firstBook",
"instore" : true
}
]
},
{
"title": "Charger",
"items" : [
{
"name" : "firstCharger",
"instore" : true
}
]
},
{
"title": "Studyroom",
"items": [
{
"name" : "firstStudyroom",
"instore" : true
}
]
},
{
"title": "Headphone",
"items":[
{
"name" : "firstHeadphone",
"instore" : true
}
]
}
]
`.
我通过JSON解码器在AppDelegate.swift文件中读取它
func parseJSON(jsonData: Data) {
let context = persistentContainer.newBackgroundContext()
let contextForItem = persistentContainer.newBackgroundContext()
do {
let decoder = JSONDecoder()
decoder.userInfo[CodingUserInfoKey.context!] = context
let decodedData = try decoder.decode([Category].self, from: jsonData)
for category in decodedData {
let newCategory = Category(context: context)
newCategory.title = category.title
if let itemArray = category.items {
for item in itemArray {
let newItem = Item(context: contextForItem)
newItem.name = item.name
newItem.instore = item.instore
newItem.parentCategory = category
itemData.append(newItem)
try contextForItem.save()
print(newItem.parentCategory.title)
}
} else {
print("nothing in the set")
}
categoryModel.append(newCategory)
}
print(categoryModel.count)
print(itemData.count)
try context.save()
} catch {
print("error while decoding the JSON file, \(error)")
}
}
但是,当我使用fetch请求在viewController中加载类别和项目时,我总是会找到类别的数量,并且项目会加倍,变成8个。我想知道这是否与上下文有关?如何加载正确数量的项目?以下是我在viewController中使用的加载函数:
func loadCategories() {
let fetchRequest = Category.fetchRequest() as! NSFetchRequest<Category>
do {
print("before fetching \(categories.count)")
categories = try context.fetch(fetchRequest)
print("afterLoading \(categories.count)")
} catch {
print ("Error while loading Categories \(error)")
}
self.collectionView.reloadData()
}
func loadCategories(){
将fetchRequest=Category.fetchRequest()设为!NSFetchRequest
做{
打印(“在获取\(categories.count)之前”)
categories=try context.fetch(fetchRequest)
打印(“后加载\(categories.count)”)
}抓住{
打印(“加载类别时出错\(错误)”)
}
self.collectionView.reloadData()
}
当然可以。为什么要使用两种上下文?为什么要在AppDelegate中解析JSON,而不是在NSManagedObject
子类中解析JSON?您建议我怎么做?您提到的子类是手动创建的吗?我对此很困惑。谢谢你回答我@瓦迪安,请见见,非常感谢!我已经应用了这段代码,但是我从来没有注意到一旦解码过程完成,就应该保存上下文。我不应该使用两个for循环来指定每个category和items数据模型,这可能会再次复制上下文。我现在已经解决了这个问题@vadian你当然可以。为什么要使用两种上下文?为什么要在AppDelegate中解析JSON,而不是在NSManagedObject
子类中解析JSON?您建议我怎么做?您提到的子类是手动创建的吗?我对此很困惑。谢谢你回答我@瓦迪安,请见见,非常感谢!我已经应用了这段代码,但是我从来没有注意到一旦解码过程完成,就应该保存上下文。我不应该使用两个for循环来指定每个category和items数据模型,这可能会再次复制上下文。我现在已经解决了这个问题@vadian