重新启动应用程序后,核心数据将删除数据

时间:2019-03-13 14:46:10

标签: ios arrays swift core-data migration

我更改了结构并进行了迁移(创建了新模型),添加并显示了数据,一切正常,但是当我重新加载应用程序时,核心数据为空,是什么问题?

  static func saveToCoreData(_ words: Words?){

    DispatchQueue.main.async {

        coreDataResult(data: [words?.word, words?.translation], completion: { (result, taskObject, context) in
            do {
                let fetchedEntities = try context.fetch(result) as! [Favorite]
                if let _ = fetchedEntities.first?.word {
                    print("the element already have in coreData")
                } else {

                    taskObject?.setValue(words?.word, forKey: "word")
                    taskObject?.setValue(words?.translation, forKey: "translation")
                    taskObject?.setValue(words?.descript, forKey: "wordDesc")
                    taskObject?.setValue(words?.translDesc, forKey: "translDesc")

                    do {
                        try context.save()
                    } catch {
                        print(error)
                    }
                }
            } catch {}
        })

    }

}

static func coreDataResult(data: [[String?]?]?, completion: @escaping (NSFetchRequest<NSFetchRequestResult>, Favorite?, NSManagedObjectContext) -> ()){

    guard let w = data?.first, let word = w, let t = data?.last, let transl = t else { return }

    DispatchQueue.main.async {
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        let context = appDelegate.persistentContainer.viewContext
        guard let entity = NSEntityDescription.entity(forEntityName: "Favorite", in: context) else { return }
        guard let taskObject = NSManagedObject(entity: entity, insertInto: context) as? Favorite else { return }

        let predicate = NSPredicate(format: "word == %@", word)
        let predicate2 = NSPredicate(format: "translation == %@", transl)
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Favorite")
        let andPredicate = NSCompoundPredicate(type: .and, subpredicates: [predicate, predicate2])

        fetchRequest.predicate = andPredicate
        completion(fetchRequest, taskObject, context)
    }

}

旧属性   old Attributes

新属性 new Attributes

新型号
new Model

1 个答案:

答案 0 :(得分:1)

我决定了

此答案对我有帮助-https://stackoverflow.com/a/40662940/8070211

  1. 创建模型(命令+ n -> 映射模型-> 选择旧模型-> 选择新模型 >-> 添加名称并创建enter image description here
  2. 创建子类NSEntityMigrationPolicy

    class FavoriteEntityMigrationPolicy: NSEntityMigrationPolicy {
    
       @objc func typeFor(word:String) -> [String] {
           return [word]
       }
    
    }
    
  3. 选择模型-> 选择实体-> 将子类添加到自定义策略 enter image description here

    < / li>
  4. 选择模型-> 选择实体-> 选择值表达式-> 添加 {{ 1}} enter image description here

  5. 准备好了