如何在Swift3中向实体插入新数据? [英] How to insert new data to entity in Swift3?
问题描述
以前,我能够使用这样的代码将新数据添加到我的数据模型中的"TestEntity"中.
In swift previously, I was able to use a code like this to add new data to my "TestEntity" in my data model.
NSManagedObject
是为我的"TestEntity"创建的,我能够使用点"语法设置其属性
NSManagedObject
was created for my "TestEntity" and I was able to set its attributes with the "dot" syntax
最后,我要保存上下文
let entity=NSEntityDescription.insertNewObject(forEntityName: "TestEntity", into: context) as! TestEntity
entity.testAttribute="test value"
context.save()
此代码在Swift3中不起作用.当我运行它时,出现以下运行时错误:
This code does not work in Swift3. When I run it, i get the following runtime error:
无法转换类型为'NSManagedObject_TestEntity_'的值 (0x175306b0)到'testCoreData.TestEntity'(0xd6bb8). 2016-06-19 11:07:52.305195 testCoreData [689:264453]无法转换类型的值 将'NSManagedObject_TestEntity_'(0x175306b0)更改为 'testCoreData.TestEntity'(0xd6bb8)
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中完成此操作吗?任何帮助都将受到高度赞赏. 谢谢.
Can anyone shed some light on how this should be done in swift3, please? Any help is highly appreciated. Thank you.
问题的第二部分是如何再次访问数据.以下代码以错误结尾:致命错误:NSArray
元素与Swift Array元素类型不匹配
The second part of the question is how to access the data again. the following code ends with an error: fatal error: NSArray
element failed to match the Swift Array Element type
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
,则新语法为
If there is a NSManagedObject
subclass TestEntity
the new syntax is
let entity = TestEntity(context: context)
entity.testAttribute="test value"
这篇关于如何在Swift3中向实体插入新数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!