EXC_BAD_ACCESS error for NSManagedObject implementing protocol in Swift

I have the following two methods:

func isAuthenticated() -> Bool {
    var currentUser: CurrentUser? = self.getCurrentUser()

    if currentUser == nil {
        return false
    }

    self.token = getUserToken(currentUser!.username)
    if self.token == nil {
        return false
    }

    if !tokenIsValidForUser(self.token!, user: currentUser!) {
        return false
    }

    return true
}

func tokenIsValidForUser(token: AuthenticationToken, user: UserObject) -> Bool {
    if token.username != user.username {
        return false
    }

    return true
}

      

When I call isAuthenticated()

it fails on the first line tokenIsValidForUser()

with EXC_BAD_ACCESS

apparently on the CurrentUser object.

My understanding si is that you get an error like this when the object no longer exists, but I can't figure out why that would be the case.

The object type CurrentUser is declared as:

protocol UserObject {
    var username: String { get set }
}

class CurrentUser: NSManagedObject, UserObject {

    @NSManaged var username: String

}

      

+3


source to share


1 answer


I found a solution to this problem here:

http://lesstroud.com/dynamic-dispatch-with-nsmanaged-in-swift/



Basically, this is Swift's quirk when it comes to implementing protocols for NSManaged objects. I had to add a keyword dynamic

to my @NSManaged properties in the CurrentUser class to make the class look like this:

class CurrentUser: NSManagedObject, UserObject {

    @NSManaged dynamic var username: String

}

      

+6


source







All Articles