加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何在Swift3中向实体插入新数据?

发布时间:2020-12-14 05:31:09 所属栏目:百科 来源:网络整理
导读:在之前的 swift中,我能够使用这样的代码将新数据添加到我的数据模型中的“TestEntity”中. NSManagedObject是为我的“TestEntity”创建的,我能够使用“dot”语法设置其属性 最后,我会保存上下文 let entity=NSEntityDescription.insertNewObject(forEntityNa
在之前的 swift中,我能够使用这样的代码将新数据添加到我的数据模型中的“TestEntity”中.

NSManagedObject是为我的“TestEntity”创建的,我能够使用“dot”语法设置其属性

最后,我会保存上下文

let entity=NSEntityDescription.insertNewObject(forEntityName: "TestEntity",into: context) as! TestEntity
entity.testAttribute="test value"
context.save()

此代码在Swift3中不起作用.当我运行它时,我得到以下运行时错误:

Could not cast value of type ‘NSManagedObject_TestEntity_’
(0x175306b0) to ‘testCoreData.TestEntity’ (0xd6bb8). 2016-06-19
11:07:52.305195 testCoreData[689:264453] Could not cast value of type
‘NSManagedObject_TestEntity_’ (0x175306b0) to
‘testCoreData.TestEntity’ (0xd6bb8)

任何人都可以了解如何在swift3中完成这项工作,好吗?任何帮助都非常感谢.
谢谢.

问题的第二部分是如何再次访问数据.以下代码以错误结束:致命错误:NSArray元素无法与Swift数组元素类型匹配

let fr:NSFetchRequest<TestEntity>=TestEntity.fetchRequest()

do {
   let searchResults=try context.fetch(fr)
   if let results=searchResults {
      for result in results {
         print("testAtt = (result.testAtt)")
      }
   }
} catch {

}
如果有一个NSManagedObject子类TestEntity,则新语法为
let entity = TestEntity(context: context)
entity.testAttribute="test value"

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读