Swift Gives error Thread 1: EXC_BAD_ACCESS(code=1, address=0x0) when accessing NSManagedObject's property

耗尽温柔 提交于 2019-12-12 03:17:04

问题


My function to create NSManagedObject's subclass object is;

func loginMoldelWithName(name: NSString, atIndexPath indexPath: NSIndexPath) -> LoginModel {

    let entity = NSEntityDescription.entityForName("LoginModel", inManagedObjectContext: managedObjectContext!)

    var login = LoginModel(entity: entity!, insertIntoManagedObjectContext: managedObjectContext)

    login.name = name
    login.date = NSDate()
    login.rowIndex = indexPath.row as NSNumber

    var error: NSError?
    if !managedObjectContext!.save(&error) {
        println("\(TAG) Could not save \(error), \(error?.userInfo)")
    }

    return login as LoginModel 

}

And the one to delete;

func deleteLoginModel(loginModel: LoginModel) {
    println("\(TAG)  \(loginModel.name)")
    managedObjectContext?.deleteObject(loginModel)

    var error : NSError?
    if(managedObjectContext!.save(&error) ) {
        println("\(TAG) \(error?.localizedDescription)")
    }
}

And where the issue occurs is at;

let loginModel = loginModels[indexPath.row] as LoginModel
println("\(TAG) \(loginModel.name)")
// remove from Core Data
deleteLoginModel(loginModel)
...

After removing loginModel object when i try to access the loginModel.name, i'm getting the error "Thread 1: EXC_BAD_ACCESS(code=1, address=0x0)"

Invalid expression is written for loginModel in the variables view, see the snaphsot below...

I can't find where i did wrong and what could have happened to the loginModel instance ?


回答1:


From the screenshot you attached, it looks like the error is occurring because you are trying to access the property of an object after that object has been deleted. At that point, the properties of the object will no longer be valid memory addresses.



来源:https://stackoverflow.com/questions/28092971/swift-gives-error-thread-1-exc-bad-accesscode-1-address-0x0-when-accessing-n

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