ios - Cant Fetch CoreData Attribute Value When UITableView Is Empty -
i have app adds amount 5 core data attribute value every time swipe delete tableviewcell function used. core data configuration looks like: https://i.stack.imgur.com/16yr6.png code in commit editingstyle class looks like:
if editingstyle == uitableviewcelleditingstyle.delete{ let fetchrequest: nsfetchrequest<goal> = goal.fetchrequest() { let array_users = try context.fetch(fetchrequest) let user = array_users[0] var count: int64 = user.value(forkey: "totalgold") as! int64 count += 5 user.setvalue(count, forkey: "totalgold") let str = string(describing: user.value(forkey: "totalgold") as! int64) totalgold.text = str { try context.save() print("saved!") } catch let error nserror { print("could not save \(error), \(error.userinfo)") } catch { } } catch { print("error request: \(error)") } let managedobject: nsmanagedobject = controller.object(at: indexpath) nsmanagedobject; context.delete(managedobject) ad.savecontext() } }
then use same fetching process in viewdidload, so:
let fetchrequest: nsfetchrequest<goal> = goal.fetchrequest() { let array_users = try context.fetch(fetchrequest) let user = array_users[0] let count: int64 = user.value(forkey: "totalgold") as! int64 user.setvalue(count, forkey: "totalgold") let str = string(describing: user.value(forkey: "totalgold") as! int64) totalgold.text = str //save context { try context.save() print("saved!") } catch let error nserror { print("could not save \(error), \(error.userinfo)") } catch { } } catch { print("error request: \(error)") }
this code works fine every case unless there no table view cells in table view. then, when try reload view while there no cells, index out of range error while trying fetch on line :
let user = array_users[0]
obviously, due fact when try fetch latest value totalgold, can't find , thinks theres no values, i'm doing fetching wrong. how fetch latest attribute value totalgold?
you can put in condition
let fetchrequest: nsfetchrequest<goal> = goal.fetchrequest() { let array_users = try context.fetch(fetchrequest) if array_users.count > 0 { let user = array_users[0] let count: int64 = user.value(forkey: "totalgold") as! int64 user.setvalue(count, forkey: "totalgold") let str = string(describing: user.value(forkey: "totalgold") as! int64) totalgold.text = str //save context { try context.save() print("saved!") } catch let error nserror { print("could not save \(error), \(error.userinfo)") } catch { } } } catch { print("error request: \(error)") }
Comments
Post a Comment