问题描述
我有以下两种方法:
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
}
当我调用 isAuthenticated()
时, c $ c> tokenIsValidForUser()与 EXC_BAD_ACCESS
,显然在CurrentUser对象上。
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.
对象类型CurrentUser被声明as:
The object type CurrentUser is declared as:
protocol UserObject {
var username: String { get set }
}
class CurrentUser: NSManagedObject, UserObject {
@NSManaged var username: String
}
推荐答案
我在这里找到了这个问题的解决方案:
I found the solution to this issue here:
本质上,当在NSManaged对象上实现协议时,这是Swift的一个奇怪。我不得不在CurrentUser类中的@NSManaged属性中添加 dynamic
关键字,以使类看起来像这样:
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
}
这篇关于NSManagedObject在Swift中实现协议时发生EXC_BAD_ACCESS错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!