swift_dynamicCastClassUnconditional issues in swif

2019-03-01 11:26发布

问题:

I have the following NSManagedObject in swift:

import Foundation
import CoreData

public class User: NSManagedObject {

    @NSManaged public var first_name: String
    @NSManaged public var last_name: String
}

I have a class which provides the value with a function below:

- (id)getUserAtIndexPath:(NSIndexPath *)indexPath {
    User *user = [self.fetchedResultsController objectAtIndexPath:indexPath];
    return user;
}

When I call this function from an Objective-C class, everything works fine. I call like so:

User *user = [self.userAccessor getUserAtIndexPath:indexPath];

And i'm able to continue from there. When I call it from a Swift class like so:

let user: User = self.userAccessor.getUserAtIndexPath(indexPath) as User

I get the swift_dynamicCastClassUnconditional every time. Is there anything i'm doing wrong? Why is the same function working in Objective-C and not Swift? I even put a break point and can confirm on the Swift call the return is a valid variable! Some how Swift is just missing it.

I tried reading the below on this:

http://jamesonquave.com/blog/understanding-the-fatal-error-cant-unwrap-optional-none-errors-in-swift/

AnyObject array returned by NSFetchRequest errors with "Swift dynamic cast failed" upon cast in Swift XCode 6 Beta 4 in XCTestCase

Is there anything else i'm missing?

回答1:

I got the solution here:

Swift: Breakpoint in CoreData library

Basically I had to put @objc(User) right above managed object code. So as per below:

@objc(User)
public class User: NSManagedObject {
    @NSManaged public var first_name: String
    @NSManaged public var last_name: String
}

This solved the problem. Case closed.