How to insert new data to entity in Swift3?

matyasl picture matyasl · Jun 19, 2016 · Viewed 7.8k times · Source

In swift previously, I was able to use a code like this to add new data to my "TestEntity" in my data model.

NSManagedObject was created for my "TestEntity" and I was able to set its attributes with the "dot" syntax

At the end, I would save the context

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

This code does not work in Swift3. When I run it, i get the following runtime error:

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)

Can anyone shed some light on how this should be done in swift3, please? Any help is highly appreciated. Thank you.

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 {

}

Answer

vadian picture vadian · Jun 19, 2016

If there is a NSManagedObject subclass TestEntity the new syntax is

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