ios - Check for Saved IDs in Core Data database and show/hide button “Add to Fav” in Swift 3 -
i have profile view controller (vc1), , on vc1 have button says "add favourite". when tap button, able save details (id , profile name) in core data database , able see data/s in table list view inside fav view controller (vc2). now, when go vc2, can see favourites in table list , when click on 1 of record, show me details of profile.
but problem is, button have here "add favourite", need change "remove favourite" profile marked favourite.
i able understand concept, obj id needs check in database , if there match button.settitle change , required function. not able figure out correctly.
thanks time, appreciate!!!
my code saving data
@iboutlet weak var fav_remove_fav_button_label: uibutton! @ibaction func savefav(_ sender: any) { var proid = saved_id let context = (uiapplication.shared.delegate as! appdelegate).persistentcontainer.viewcontext let task = favprofile(context: context) // link task & context task.busname = bussinessname task.profileid = int32(id!)! print ("saved id is: - \(task.profileid)") print ("saved profile name is: - \(task.busname)") fav_remove_fav_button_label.settitle("remove favourite", for: .normal) // save data coredata (uiapplication.shared.delegate as! appdelegate).savecontext() // let _ = navigationcontroller?.popviewcontroller(animated: true) let alert = uialertcontroller(title: "alert", message: "added favourite list", preferredstyle: uialertcontrollerstyle.alert) alert.addaction(uialertaction(title: "ok", style: uialertactionstyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) }
my function fetch , check data
func isexist(id: int) -> bool { var error: nserror? var moc: nsmanagedobjectcontext! var fetchrequest = nsfetchrequest<nsfetchrequestresult>(entityname: "favprofile") if let results = try! moc.fetch(fetchrequest) as? [favprofile] { if !results.isempty { x in results { if x.profileid == int32(id) { print("already exist") moc.delete(x) } } } } else { print(error) } return false }
try ->
func isexist(id: int) -> bool { let context = (uiapplication.shared.delegate as! appdelegate).persistentcontainer.viewcontext var error: error? = nil let fetch = nsfetchrequest<nsfetchrequestresult>() let entitydescription = nsentitydescription.entity(forentityname: "favprofile", in: context) fetch.entity = entitydescription as? nsentitydescription! nsentitydescription() fetch.predicate = nspredicate(format: "profileid == %d", id) let fetchedobjects: [any]? = try? context.fetch(fetch) if error != nil { return false } else { if (fetchedobjects?.count)! > 0 { print("fetchedobjects--->found"); return true } else { print("fetchedobjects--->nil"); return false } } } override func viewdidload() { super.viewdidload() // favbuttonlabel() // isexist(id: 182397) let favcheck: bool = isexist(id:182397) if favcheck == true { print("favourite--->"); } }
Comments
Post a Comment