然后继续测试的时候,发现许多时候输出的JSON里面只有一部分字段被输入回来,比如说6个Application可能只有3个被导入回来,报错内容是「Invalid
number of keys found, expected one」。
考虑到之前也遇到带关联值的enum decode回来的时候出现「Invalid number
of keys found, expected one」的错误,也就参考这里试着实现了一个手动decode/encode的实现,不过这个思路会导致程序直接在新建对象后报错,原因是访问enum的时候出错,所以这个思路也就只能放弃了。
... let decoded =try decoder.decode([Company].self, from: data)
/// Mark: Processing de-duplication of entries
// Fetch descriptors for retrieving SwiftData data let categoryDescriptor =FetchDescriptor<Category>(sortBy: [SortDescriptor(\.name)]) let descriptionDescriptor =FetchDescriptor<Description>()
// find out all inserted types and get un-duplicate names let insertedTypes =try modelContext.fetch(categoryDescriptor) let categoryNames =Set(insertedTypes.map { $0.name })
// Build two groups of these category types: first occurences of each one; and their duplicata let firstCategories = categoryNames.map { name in insertedTypes.first(where: { $0.name == name }) } let duplicatedCategories = insertedTypes.filter { !firstCategories.contains($0) }
// Retrieve all descriptions let existingDescs =try modelContext.fetch(descriptionDescriptor)
// Rearrange category types in case of duplicata existingDescs.forEach { job in iflet match = duplicatedCategories.first(where: { $0== job.type }) { job.type = firstCategories.first(where: { $0!.name == match.name })! } }
// Remove all duplicated types duplicatedCategories.forEach { modelContext.delete($0) }