在之前的
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"