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

前端之家收集整理的这篇文章主要介绍了如何在Swift3中向实体插入新数据?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在之前的 swift中,我能够使用这样的代码将新数据添加到我的数据模型中的“TestEntity”中.

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

最后,我会保存上下文

  1. let entity=NSEntityDescription.insertNewObject(forEntityName: "TestEntity",into: context) as! TestEntity
  2. entity.testAttribute="test value"
  3. 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数组元素类型匹配

  1. let fr:NSFetchRequest<TestEntity>=TestEntity.fetchRequest()
  2.  
  3. do {
  4. let searchResults=try context.fetch(fr)
  5. if let results=searchResults {
  6. for result in results {
  7. print("testAtt = \(result.testAtt)")
  8. }
  9. }
  10. } catch {
  11.  
  12. }
如果有一个NSManagedObject子类TestEntity,则新语法为
  1. let entity = TestEntity(context: context)
  2. entity.testAttribute="test value"

猜你在找的Swift相关文章