ios - Fetching Core Data row by name? -


i'm on new project encountering difficulties regrind fetch requests in swift.

basically setup looks following.

entity "plants" - name, info, plant2 (placeholder far) entity "plantlog" - name, date, erg, cmt, fertilizer

i have tableview "plants" in , can update plant information such name, info , "plant2". when have button called "add log" in name of plant given new view:

 if segue.identifier == "addlog"     {          var existingplant: string = textfieldname.text         let ivc: addplantviewcontroller = segue.destinationviewcontroller as! addplantviewcontroller         ivc.name = existingplant       } 

this works perfectly. saving plantlog entity name , other stuff. comes problem --> when click on save should perform segue action in updates tableview plant log entries "name" lets call "pachira" displayed , segue "show e.g. push" gives values plantdetail page.

@ibaction func testfetch(sender: anyobject) {       var error: nserror?     let fetchrequest = nsfetchrequest(entityname: "plants")     let appdel: appdelegate = uiapplication.sharedapplication().delegate as! appdelegate     let contxt: nsmanagedobjectcontext = appdel.managedobjectcontext!     let fetchresults = contxt.executefetchrequest(fetchrequest, error: &error)      let predicate = nspredicate(format: "name == %@", name)       //fetchrequest.predicate = predicate       // var data: nsmanagedobject = fetchresults as! nsmanagedobject    // labelname.text = predicate   } 

this test if fetch row name "pachira" can't find solution fetch "pachira" "info" , "plant2" core data.

you give no information crash, of commented out lines, having problems accessing results of fetch. first, need set predicate fetch request before execute fetch. then, return value executefetchrequest array - if there 1 matching object. rearrange fetch follows:

var error: nserror? let fetchrequest = nsfetchrequest(entityname: "plants") let predicate = nspredicate(format: "name == %@", name) fetchrequest.predicate = predicate let appdel: appdelegate = uiapplication.sharedapplication().delegate as! appdelegate let contxt: nsmanagedobjectcontext = appdel.managedobjectcontext! let fetchresults = contxt.executefetchrequest(fetchrequest, error: &error) // should check whether fetchresults nil, , if log error.  //  should ensure @ least 1 object returned. let object = fetchresults![0] println("\(object)") 

Comments