1

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?

Community
  • 1
  • 1
KVISH
  • 12,923
  • 17
  • 86
  • 162
  • Perhaps the cast should be `User?` instead of `User`? – Léo Natan Oct 10 '14 at 20:14
  • When I do that, i get `nil` when i do `println(user)` in swift. – KVISH Oct 10 '14 at 20:19
  • That means your get method is having trouble. You are not allowed to typecast nil without an error (it's actually one of the definitions I've seen of a proper `undefined` function). – CodaFi Oct 11 '14 at 00:37
  • I got the solution below. It's working fine on the `Objective-C` side--I see with breakpoints getting the values properly. It's just not passing to `Swift` for some reason. – KVISH Oct 11 '14 at 00:38
  • I had to add the `@objc(User)` as per below. – KVISH Oct 11 '14 at 00:38
  • A lot of Core Data, KVO, anything that requires introspection, etc. will break if Swift stuff isn't marked @objc or dynamic. – CodaFi Oct 11 '14 at 00:41

1 Answers1

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.

Community
  • 1
  • 1
KVISH
  • 12,923
  • 17
  • 86
  • 162