swift - CoreData - PickerView updating a tableView -


look code:

models:

import foundation import coredata  class trainingdetails: nsmanagedobject {      @nsmanaged var exercisename: string     @nsmanaged var repsnumber: string     @nsmanaged var setsnumber: string     @nsmanaged var trainingday: trainingday  } 

and

import foundation import coredata  class trainingday: nsmanagedobject {      @nsmanaged var day: string     @nsmanaged var dayindex: nsnumber     @nsmanaged var trainingdetails: nsset  } 

and function here:

func pickerview(pickerview: uipickerview, didselectrow row: int, incomponent component: int) {          let currentday = daysarray[row]          let fetchrequest = nsfetchrequest(entityname: "trainingdetails")         let predicate = nspredicate(format: "trainingday.day == %@", currentday)         fetchrequest.predicate = predicate         let sort = nssortdescriptor(key: "exercisename", ascending: true)         fetchrequest.sortdescriptors = [sort]         detailsarray = (moc!.executefetchrequest(fetchrequest, error: nil) as? [trainingdetails])!         exercisetableview.reloaddata()     } 

now, can see, have pickerview should update tableview everytime selected different option inside it, that's not happening. know instead of let currentday = daysarray[row] should attribute fetchedresultscontroller coredata currentday, try update tableview.

my question is: right think this? how do it?

i'm new swift, love examples on how it.

thanks in advance!!

update -> full code

import uikit import coredata  class exerciseviewcontroller: uiviewcontroller, uitableviewdelegate, uitableviewdatasource, uipickerviewdatasource, uipickerviewdelegate, nsfetchedresultscontrollerdelegate {      override func viewdidload() {         super.viewdidload()          vdl()          //sets stepper configs         setsstepper.wraps = false         setsstepper.autorepeat = true         setsstepper.continuous = true         setsstepper.tintcolor = uicolor.redcolor()         setsstepper.minimumvalue = 0         setsstepper.maximumvalue = 500         setsstepper.value = 0          //reps stepper configs         repsstepper.wraps = false         repsstepper.autorepeat = true         repsstepper.continuous = true         repsstepper.tintcolor = uicolor.orangecolor()         repsstepper.minimumvalue = 0         repsstepper.maximumvalue = 500         repsstepper.value = 0          exercisetableview.reloaddata()     }      var moc = (uiapplication.sharedapplication().delegate as! appdelegate).managedobjectcontext     var fetchedresultscontroller: nsfetchedresultscontroller?      @iboutlet var exercisetableview: uitableview!      @iboutlet var dayspickerview: uipickerview!      @iboutlet var exercisename: uitextfield!     @iboutlet var setsstepper: uistepper!     @iboutlet var repsstepper: uistepper!      @iboutlet var setsnumber: uilabel!     @iboutlet var repsnumber: uilabel!      var daysarray = [trainingday]()     var detailsarray = [trainingdetails]()      func vdl () {          let fetchrequest = nsfetchrequest(entityname: "trainingday")         let sort = nssortdescriptor(key: "dayindex", ascending: true)         fetchrequest.sortdescriptors = [sort]         daysarray = (moc!.executefetchrequest(fetchrequest, error: nil) as? [trainingday])!         if daysarray.count == 0 { // nothing there             let dayentity = nsentitydescription.entityforname("trainingday", inmanagedobjectcontext: moc!)             let days = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"]             (index, name) in enumerate(days) {                 let newday = trainingday(entity: dayentity!, insertintomanagedobjectcontext: moc)                 newday.day = name                 newday.dayindex = index                 daysarray.append(newday)                 println("name: \(newday.day) index: \(newday.dayindex)")             }             var error: nserror?             moc!.save(&error)         }     }       func appendtrainingdetailstoarray () {         let row = dayspickerview.selectedrowincomponent(0)         let currentday = daysarray[row]          let detailsentity = nsentitydescription.entityforname("trainingdetails", inmanagedobjectcontext: moc!)         let trainingdetails = trainingdetails(entity: detailsentity!, insertintomanagedobjectcontext: moc)         trainingdetails.exercisename = exercisename.text         trainingdetails.repsnumber = repsnumber.text!         trainingdetails.setsnumber = setsnumber.text!         trainingdetails.trainingday = currentday          var error: nserror?         moc?.save(&error)          if let err = error {             var status = err.localizedfailurereason             println("\(status)")         } else {             println("current setting: \(trainingdetails.trainingday)")         }     }      func fetchtrainingdetails() -> nsfetchrequest {          let fetchrequest = nsfetchrequest(entityname: "trainingdetails")         fetchrequest.predicate = nil         let sortdescriptor = nssortdescriptor(key: "trainingday", ascending: true)         fetchrequest.sortdescriptors = [sortdescriptor]         fetchrequest.fetchbatchsize = 20         return fetchrequest     }      @ibaction func donebutton(sender: anyobject) {         appendtrainingdetailstoarray()         fetchedresultscontroller = nsfetchedresultscontroller(fetchrequest: fetchtrainingdetails(), managedobjectcontext: moc!, sectionnamekeypath: nil, cachename: nil)         fetchedresultscontroller?.delegate = self         fetchedresultscontroller?.performfetch(nil)         exercisetableview.reloaddata()     }      @ibaction func setsstepperaction(sender: uistepper) {         println("\(int(sender.value))")         setsnumber.text = int(sender.value).description     }      @ibaction func repsstepper(sender: uistepper) {         println("\(int(sender.value))")         repsnumber.text = int(sender.value).description     }      func numberofsectionsintableview(tableview: uitableview) -> int {         return fetchedresultscontroller?.sections?.count ?? 0     }      func tableview(tableview: uitableview, numberofrowsinsection section: int) -> int {         return fetchedresultscontroller?.sections?[section].numberofobjects ?? 0     }      func tableview(tableview: uitableview, cellforrowatindexpath indexpath: nsindexpath) -> uitableviewcell {          let cell = tableview.dequeuereusablecellwithidentifier("exercisecell", forindexpath: indexpath) as! uitableviewcell         let details = fetchedresultscontroller!.objectatindexpath(indexpath) as! trainingdetails         cell.textlabel!.text = "\(details.exercisename)"         cell.detailtextlabel!.text = "sets: #\(details.setsnumber) reps: #\(details.repsnumber)"          return cell     }      func tableview(tableview: uitableview, caneditrowatindexpath indexpath: nsindexpath) -> bool {         if self.fetchedresultscontroller == nil {             return false         } else {             return true         }     }      func tableview(tableview: uitableview, commiteditingstyle editingstyle: uitableviewcelleditingstyle, forrowatindexpath indexpath: nsindexpath) {         println("section , row \(indexpath.section) \(indexpath.row) ")         if self.fetchedresultscontroller == nil {             println("error when trying delete object managed object")          } else if (editingstyle == uitableviewcelleditingstyle.delete) {              switch editingstyle {             case .delete:                 moc?.deleteobject(fetchedresultscontroller?.objectatindexpath(indexpath) as! trainingdetails)                 moc?.save(nil)             case .insert:                 break             case .none:                 break             }         }     }      //picker view delegate , datasource methods     func numberofcomponentsinpickerview(pickerview: uipickerview) -> int {         return 1     }      func pickerview(pickerview: uipickerview, numberofrowsincomponent component: int) -> int {         return daysarray.count     }      func pickerview(pickerview: uipickerview, titleforrow row: int, forcomponent component: int) -> string! {             let trainingday = daysarray[row]             return trainingday.day     }      func pickerview(pickerview: uipickerview, didselectrow row: int, incomponent component: int) {          let currentday = daysarray[row]          let fetchrequest = nsfetchrequest(entityname: "trainingdetails")         let predicate = nspredicate(format: "trainingday.day == %@", currentday)         fetchrequest.predicate = predicate         let sort = nssortdescriptor(key: "exercisename", ascending: true)         fetchrequest.sortdescriptors = [sort]         detailsarray = (moc!.executefetchrequest(fetchrequest, error: nil) as? [trainingdetails])!         exercisetableview.reloaddata()     }      // mark: nsfetchedresultscontrollerdelegate     func controllerwillchangecontent(controller: nsfetchedresultscontroller) {         self.exercisetableview.beginupdates()     }     func controller(controller: nsfetchedresultscontroller,         didchangeobject anobject: anyobject,         atindexpath indexpath: nsindexpath?,         forchangetype type: nsfetchedresultschangetype,         newindexpath: nsindexpath?)     {         switch type {         case nsfetchedresultschangetype.insert:             // note insert, insert row @ __newindexpath__             if let insertindexpath = newindexpath {                 self.exercisetableview.insertrowsatindexpaths([insertindexpath], withrowanimation: uitableviewrowanimation.fade)             }         case nsfetchedresultschangetype.delete:             // note delete, delete row @ __indexpath__             if let deleteindexpath = indexpath {                 self.exercisetableview.deleterowsatindexpaths([deleteindexpath], withrowanimation: uitableviewrowanimation.fade)             }         case nsfetchedresultschangetype.update:             // note update, update row @ __indexpath__             if let updateindexpath = indexpath {                 let cell = self.exercisetableview.cellforrowatindexpath(updateindexpath)                 let details = self.fetchedresultscontroller!.objectatindexpath(updateindexpath) as? trainingdetails                  cell!.textlabel!.text = "\(details!.exercisename)"                 cell!.detailtextlabel!.text = "sets: #\(details!.setsnumber) reps: #\(details!.repsnumber)"             }         case nsfetchedresultschangetype.move:             // note move, delete row @ __indexpath__             if let deleteindexpath = indexpath {                 self.exercisetableview.deleterowsatindexpaths([deleteindexpath], withrowanimation: uitableviewrowanimation.fade)             }              // note move, insert row @ __newindexpath__             if let insertindexpath = newindexpath {                 self.exercisetableview.insertrowsatindexpaths([insertindexpath], withrowanimation: uitableviewrowanimation.fade)             }         }    }      func controller(controller: nsfetchedresultscontroller,         didchangesection sectioninfo: nsfetchedresultssectioninfo,         atindex sectionindex: int,         forchangetype type: nsfetchedresultschangetype)     {         switch type {         case .insert:             let sectionindexset = nsindexset(index: sectionindex)             self.exercisetableview.insertsections(sectionindexset, withrowanimation: uitableviewrowanimation.fade)         case .delete:             let sectionindexset = nsindexset(index: sectionindex)             self.exercisetableview.deletesections(sectionindexset, withrowanimation: uitableviewrowanimation.fade)         default:             ""         }     }     func controllerdidchangecontent(controller: nsfetchedresultscontroller) {         exercisetableview.endupdates()     } } 

so, need change fetch request associated fetchedresultscontroller, , invoke performfetch() on it, , reload table view. in

 func pickerview(pickerview: uipickerview, didselectrow row: int, incomponent component: int) {   let currentday = daysarray[row]         //update fetch request related fetchedresultscontroller.fetchrequest table view controller uses data         let fetchrequest = fetchedresultscontroller.fetchrequest         let predicate = nspredicate(format: "trainingday.day == %@", currentday)         fetchrequest.predicate = predicate         let sort = nssortdescriptor(key: "exercisename", ascending: true)         fetchrequest.sortdescriptors = [sort]         //perform fetch afresh         fetchedresultscontroller.performfetch(nil);          //now reload table view         exercisetableview.reloaddata() } 

refer: documentation

modifying fetch request cannot change fetch request modify results. if want change fetch request, must:

if using cache, delete (using deletecachewithname:).

typically should not use cache if changing fetch request.

change fetch request.

invoke performfetch:.


Comments

Popular posts from this blog

java - UnknownEntityTypeException: Unable to locate persister (Hibernate 5.0) -

python - ValueError: empty vocabulary; perhaps the documents only contain stop words -

ubuntu - collect2: fatal error: ld terminated with signal 9 [Killed] -