草庐IT

swift - 如何在 Swift 中向实体插入新数据?

coder 2023-07-16 原文

以前在 Swift 中,我能够使用这样的代码将新数据添加到我的数据模型中的“TestEntity”。

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

最后,我会保存上下文

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

此代码在 Swift 3 中不起作用。当我运行它时,出现以下运行时错误:

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)

谁能阐明应该如何在 Swift 3 中完成此操作?

问题的第二部分是如何再次访问数据。以下代码以错误结尾:

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 新语法是

let entity = TestEntity(context: context)
entity.testAttribute="test value"

关于swift - 如何在 Swift 中向实体插入新数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37905821/

有关swift - 如何在 Swift 中向实体插入新数据?的更多相关文章

  1. swift - 如何在 Swift 中向实体插入新数据? - 2

    以前在Swift中,我能够使用这样的代码将新数据添加到我的数据模型中的“TestEntity”。NSManagedObject是为我的“TestEntity”创建的,我能够使用“点”语法设置它的属性最后,我会保存上下文letentity=NSEntityDescription.insertNewObject(forEntityName:"TestEntity",into:context)as!TestEntityentity.testAttribute="testvalue"context.save()此代码在Swift3中不起作用。当我运行它时,出现以下运行时错误:Couldnotc

  2. swift - 如何在 Swift 中向实体插入新数据? - 2

    以前在Swift中,我能够使用这样的代码将新数据添加到我的数据模型中的“TestEntity”。NSManagedObject是为我的“TestEntity”创建的,我能够使用“点”语法设置它的属性最后,我会保存上下文letentity=NSEntityDescription.insertNewObject(forEntityName:"TestEntity",into:context)as!TestEntityentity.testAttribute="testvalue"context.save()此代码在Swift3中不起作用。当我运行它时,出现以下运行时错误:Couldnotc

随机推荐