Core Data: Could not cast value of type 'MyType_MyType_2' to MyType

前端 未结 4 1856
温柔的废话
温柔的废话 2020-12-29 21:10

I have an Objective-C model class MyType. This class is used in Swift code:

NSEntityDescription.insertNewObjectForEntit         


        
相关标签:
4条回答
  • 2020-12-29 21:29
    1. Set Entity Class Name
    2. Set Module "Current Product Module" like below

    0 讨论(0)
  • 2020-12-29 21:34

    When I had this issue, it was because I had forgotten to set the "class" on the entity. This is what I came up with:

    1. Click on .xcdatamodelId file in your file structure/project navigator pane (far left).
    2. Select the entity that you are having issues with.
    3. In the Utilities pane (far right), look for the icon that looks like a 1997 cell phone, the Data Model Inspector.
    4. Under the entity settings, you should see two fields, "Name" and "Class" - set up "Class" with the name of the class you are using (typically the same as "Name").

    You'll even notice before you follow these steps that the default "class" is NSObject, reflecting the error message. I found some programatic ways to do this too, but this seemed like the simplest/quickest solution.

    I should note that my model WAS written in Swift, so I did have to add the @objc(Entity) interoperability reference mentioned by @zellb. But that shouldn't make a difference in the solution as long as you are doing that part properly (and that would cause a different unrelated error from my understanding).

    0 讨论(0)
  • 2020-12-29 21:34

    I had mistakenly set a "parent entity" in one of my entities in the data model inspector in the entity section. I mistakenly thought that referred to the destination of a one-to-many relationship.

    Setting it back to "no parent entity" fixed the problem, although I did have to delete and reinstall the app in the simulator to deal with the messed up core data database.

    0 讨论(0)
  • 2020-12-29 21:45

    just try this:

    @objc(MyType)
    public class MyType: NSManagedObject {
        // your class
    }
    

    instead of this:

    class MyType: NSManagedObject {
        // your class
    }
    
    0 讨论(0)
提交回复
热议问题