EXC_BAD_ACCESS error for NSManagedObject implementing a protocol in Swift

风流意气都作罢 提交于 2019-12-13 14:32:36

问题


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 of tokenIsValidForUser() with EXC_BAD_ACCESS, apparently on the CurrentUser object.

My understanding si that you get this kind of error when the object no longer exists, but I cannot understand why this 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

}

回答1:


I found the solution to this issue here:

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

Essentially, this is a quirk of Swift when implementing protocols on Objects that are NSManaged. I had to add the dynamic keyword to my @NSManaged properties in the CurrentUser class, so that the class looked like this:

class CurrentUser: NSManagedObject, UserObject {

    @NSManaged dynamic var username: String

}


来源:https://stackoverflow.com/questions/25801435/exc-bad-access-error-for-nsmanagedobject-implementing-a-protocol-in-swift

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