Swift dynamicCast error while inserting new object to database

一世执手 提交于 2019-12-22 12:46:15

问题


I have a dictionary which I have all data that I want to insert into database as new object. The problem is when I try to cast the newly created object it gives me exception in:

libswift_stdlib_core.dylib`swift_dynamicCast:

part of assembly code. The code that i am using is like this:

    var group:Group  
    if (array.count == 0) {
        group = NSEntityDescription.insertNewObjectForEntityForName("Group", inManagedObjectContext:appDelegate.managedObjectContext) as Group

    }

and the structure of Group class is like this:

    @objc(Group)
    class Group:NSManagedObject{

        @NSManaged var createDate:NSString
        @NSManaged var groupPictureUrl:NSString
        @NSManaged var groupTypeId:NSString
        @NSManaged var isDepartment:NSString
        @NSManaged var lastMessageRead:NSString
        @NSManaged var name:NSString
        @NSManaged var unreadMessageCount:NSString
        @NSManaged var groupId:NSString
        @NSManaged var lastSync:NSString
}

I have also a subclass of NSManagedObject named AppData which has the same structure with Group class. And at inserting part of my code if I replace Group with AppData it works and I can insert into AppData table. As I said before they have the same structure except parameters. But when I try to insert Group object it gives me dynamic cast exception. How can I solve this problem?


回答1:


I solved the problem by initializing the entity object differently, if you implement the initiation method from super class(NSManagedObject) like: (in Group.swift)

    init(entity: NSEntityDescription!, insertIntoManagedObjectContext context: NSManagedObjectContext!) {
        super.init(entity: entity, insertIntoManagedObjectContext: context)
    } 

you can create the object like this:

    var desc:NSEntityDescription = NSEntityDescription.entityForName("Group",inManagedObjectContext:appDelegate.managedObjectContext)
    var group:Group = Group(entity:desc, insertIntoManagedObjectContext: appDelegate.managedObjectContext)

most of solutions i have read was making the initiation like this:

  var group:Group = NSEntityDescription.insertNewObjectForEntityForName("Group", inManagedObjectContext:appDelegate.managedObjectContext) as Group

so this was the problem and object could not be casted to custom managed object class with this way. Thanks to everyone.



来源:https://stackoverflow.com/questions/25200149/swift-dynamiccast-error-while-inserting-new-object-to-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!