How to insert new data to entity in Swift3?

前端 未结 4 1459
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-20 14:56

In swift previously, I was able to use a code like this to add new data to my \"TestEntity\" in my data model.

NSManagedObject was created for my \"TestEnti

4条回答
  •  半阙折子戏
    2021-02-20 15:34

    //retrieve the entity
    let entity =  NSEntityDescription.entity(forEntityName: "TestEntity", in: context)
    
    let testEntity = NSManagedObject(entity: entity!, insertInto: context)
    
    //set the entity values
    testEntity.setValue(testAtt1, forKey: "testAtt1")
    testEntity.setValue(testAtt2, forKey: "testAtt2")
    
    //save the object
    do {
        try context.save()
        print("saved!")
    } catch let error as NSError  {
        print("Could not save \(error), \(error.userInfo)")
    } catch {
    
    }
    

提交回复
热议问题