问题
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