ios - Swift 2.0 Core Data - TableView not reading NSManagedObject -
in first view controller saved data in core data uitextfields, wanted tableview read data in second view controller, got no errors got no display of data in tableview cells. in first vc made property of nsmanaged object, , in second vc retrieve object, put in tableview no data displayed. crucial understanding how tableview can read data core data, thank lot.
first vc
import uikit import coredata class viewcontroller: uiviewcontroller { @iboutlet weak var namefield: uitextfield! @iboutlet weak var passfield: uitextfield! var item = [nsmanagedobject]() override func viewdidload() { super.viewdidload() } override func didreceivememorywarning() { super.didreceivememorywarning() } @ibaction func saveinfo(sender: uibutton) { let appdel: appdelegate = uiapplication.sharedapplication().delegate as! appdelegate let context: nsmanagedobjectcontext = appdel.managedobjectcontext //add new user let newuser = nsentitydescription.insertnewobjectforentityforname("users", inmanagedobjectcontext: context) newuser.setvalue(namefield.text, forkey: "username") newuser.setvalue(passfield.text, forkey: "passwords") // add info entity do{ try context.save() }catch{ print("error, data not saved!") } // retrieve data do{ let request = nsfetchrequest(entityname: "users") let results = try context.executefetchrequest(request) if results.count > 0 { item in results as! [nsmanagedobject]{ let name = item.valueforkey("username") let password = item.valueforkey("passwords") print(name!, password!) } } }catch{ print("erorr, data not read!") } namefield.text = "" passfield.text = "" }// end of button function }
second vc aka tableview
import uikit import coredata class tableviewcontroller: uiviewcontroller, uitableviewdelegate, uitableviewdatasource { @iboutlet weak var tableview: uitableview! var bridge: viewcontroller = viewcontroller() var array = [nsmanagedobject]() override func viewdidload() { super.viewdidload() self.array = self.bridge.item self.tableview.delegate = self self.tableview.datasource = self } override func didreceivememorywarning() { super.didreceivememorywarning() // dispose of resources can recreated. } func tableview(tableview:uitableview, numberofrowsinsection section:int) -> int { return array.count } func tableview(tableview: uitableview, cellforrowatindexpath indexpath: nsindexpath) -> uitableviewcell { let cell = tableview.dequeuereusablecellwithidentifier("cell", forindexpath: indexpath) let person = array[indexpath.row] cell.textlabel!.text = person.valueforkey("username") as? string return cell } }
Comments
Post a Comment