ios - Populating Core Data into Table View -


i trying display data in custom tableview. idea in viewcontroller populate data core data entity, in viewcontroller b retrieve data core data entity , display in table view no problem. here comes problem. if delete data entity , tableview in viewcontroller b, go viewcontroller , add new item core data again, not appear in tableview when go viewcontroller b. if close , open application again, item appears there again.

so problem item appear in core data after deleting item , inserting again, doesnt appear in tableview. maybe have update tableview somehow, tried [self.tableview reloaddata]; , did not help. code below. ideas???

viewcontroller a

    #import "listitem.h" #import "vieworders.h" #import "mainview.h" #import "order_list.h" #import "appdelegate.h"  @interface listitem () @property (nonatomic, strong) nsmanagedobjectcontext *managedobjectcontext; @property (nonatomic, retain) nsfetchedresultscontroller *results; @property (nonatomic, strong) nsmutablearray *namesarray; @property (nonatomic, strong) nsmutablearray *quantityarray; @property (nonatomic, strong) nsmutablearray *pricearray; @property (nonatomic, strong) nsmutablearray *imagesarray; @end  @implementation listitem @synthesize managedobjectcontext = _managedobjectcontext; @synthesize results = _results; @synthesize imageview = _imageview; @synthesize mainview = _mainview; @synthesize namefield = _namefield; @synthesize descfield = _descfield; @synthesize pricefield = _pricefield; @synthesize quantityfield = _quantityfield; @synthesize quantitystepperoutlet = _quantitystepperoutlet; @synthesize namesarray =_namesarray; @synthesize quantityarray = _quantityarray; @synthesize pricearray = _pricearray; @synthesize imagesarray = _imagesarray;  - (void)viewdidload {     [super viewdidload];      appdelegate *delegate = (appdelegate *)[[uiapplication sharedapplication] delegate];     self.managedobjectcontext = delegate.managedobjectcontext;      //self.navigationitem.hidesbackbutton = yes;      self.namesarray = [[nsmutablearray alloc] init];     self.quantityarray = [[nsmutablearray alloc] init];     self.pricearray = [[nsmutablearray alloc] init];     self.imagesarray = [[nsmutablearray alloc] init];      uigraphicsbeginimagecontext(self.view.frame.size);     [[uiimage imagenamed:@"bella_italia_crop.png"] drawinrect:self.view.bounds];     uiimage *image = uigraphicsgetimagefromcurrentimagecontext();     uigraphicsendimagecontext();      self.view.backgroundcolor = [uicolor colorwithpatternimage:image];      uigraphicsbeginimagecontext(self.mainview.frame.size);     [[uiimage imagenamed:@"bella_italia_crop.png"] drawinrect:self.mainview.bounds];     uiimage *image2 = uigraphicsgetimagefromcurrentimagecontext();     uigraphicsendimagecontext();      self.mainview.backgroundcolor = [uicolor colorwithpatternimage:image2];      self.imageview.image = [uiimage imagenamed:self.thumbnail];     self.imageview.contentmode = uiviewcontentmodescaleaspectfit;     self.namefield.text = self.name;     self.descfield.text = self.description;     self.pricefield.text = self.price;     self.descfield.backgroundcolor = [uicolor clearcolor]; }  - (void)didreceivememorywarning {     [super didreceivememorywarning];     // dispose of resources can recreated. }  // in storyboard-based application, want little preparation before navigation - (void)prepareforsegue:(uistoryboardsegue *)segue sender:(id)sender {     if ([segue.identifier isequaltostring:@"viewallorderssegue"])     {         vieworders *vo = segue.destinationviewcontroller;         vo.namesarray = self.namesarray;         vo.quantityarray = self.quantityarray;         vo.pricearray = self.pricearray;         vo.tablenumber = @"1";         vo.imagesarray = self.imagesarray;     }      else if ([segue.identifier isequaltostring:@"unwindtomain"])     {         mainview *mv = segue.destinationviewcontroller;         mv.namesarray = self.namesarray;         mv.quantityarray = self.quantityarray;         mv.pricearray = self.pricearray;         mv.imagesarray = self.imagesarray;     } }  - (ibaction)quantitystepper:(uistepper *)sender {     int stepper = [sender value];      self.quantityfield.text = [nsstring stringwithformat:@"%d", stepper];  }  - (ibaction)addorderaction:(uibutton *)sender {     nslog(@"add order action button pressed");      order_list *newitem = [nsentitydescription insertnewobjectforentityforname:@"order_list" inmanagedobjectcontext:self.managedobjectcontext];      newitem.title = self.name;     newitem.quantity = @([self.quantityfield.text floatvalue]);     newitem.price = @([self.pricefield.text floatvalue]);     newitem.tablenumber = [nsnumber numberwithint:1];     newitem.thumbnail = self.thumbnail;     newitem.id = [nsnumber numberwithint:0];      nserror *error;     [self.managedobjectcontext save:&error];      uialertview *successalert = [[uialertview alloc] initwithtitle:@"success!" message:@"your order added orders list! press view orders finalize order or go menu , choose else." delegate:self cancelbuttontitle:@"ok" otherbuttontitles:nil, nil];     successalert.alertviewstyle = uialertviewstyledefault;     [successalert show];      nsfetchrequest *fetchrequest = [[nsfetchrequest alloc] init];     nsentitydescription *entity = [nsentitydescription entityforname:@"order_list" inmanagedobjectcontext:self.managedobjectcontext];     [fetchrequest setentity:entity];      nsarray *fetchedobjects = [self.managedobjectcontext executefetchrequest:fetchrequest error:&error];     (nsmanagedobjectcontext *info in fetchedobjects) {         nslog(@"title: %@ %@", [info valueforkey:@"title"], [info valueforkey:@"quantity"]);     }       //[self.namesarray addobject:self.name];     //[self.quantityarray addobject:self.quantityfield.text];     //int finalprice = [self.quantityfield.text intvalue] * [self.price intvalue];     //[self.pricearray addobject:[nsstring stringwithformat:@"%d", finalprice]];     //[self.imagesarray addobject:self.thumbnail];     //nslog(@"names: %@, quantities: %@, prices: %@", self.namesarray, self.quantityarray, self.pricearray); } @end 

viewcontroller b

        #import "vieworders.h" #import "appdelegate.h" #import "order_list.h" #import "vieworderscell.h"  @interface vieworders () @property (nonatomic, strong) nsmutabledata *requestdata; @property (nonatomic, strong) nsmanagedobjectcontext *managedobjectcontext; @property (nonatomic, retain) nsfetchedresultscontroller *results; @property (nonatomic, strong) nsstring* orderstate; @property (nonatomic, strong) uialertview *billalert;  @end  @implementation vieworders @synthesize managedobjectcontext = _managedobjectcontext; @synthesize results = _results; @synthesize confirmorderbutton = _confirmorderbutton; @synthesize requestdata = _requestdata; @synthesize orderstate = _orderstate; @synthesize billalert = _billalert;  - (void)viewdidload {     [super viewdidload];      self.billalert = [[uialertview alloc] initwithtitle:@"order confirmed!" message:@"your order list has been confirmed , sent kitchen! press request bill or request bill later continue (you cannot make new orders until request bill current one! trigger screen again, press , hold on order in pending orders page. thanks!)" delegate:self cancelbuttontitle:@"request bill later" otherbuttontitles:@"request bill now", nil];     self.billalert.tag = 2;     self.billalert.alertviewstyle = uialertviewstyledefault;      appdelegate *delegate = (appdelegate *)[[uiapplication sharedapplication] delegate];     self.managedobjectcontext = delegate.managedobjectcontext;     self.namesarray = [[nsmutablearray alloc] init];     self.quantityarray = [[nsmutablearray alloc] init];     self.imagesarray = [[nsmutablearray alloc] init];     self.pricearray = [[nsmutablearray alloc] init];      nsfetchrequest *corerequest = [[nsfetchrequest alloc] init];     nsentitydescription *entity = [nsentitydescription entityforname:@"order_list" inmanagedobjectcontext:self.managedobjectcontext];     [corerequest setentity:entity];     nssortdescriptor *sort = [[nssortdescriptor alloc] initwithkey:@"title" ascending:yes];     [corerequest setsortdescriptors:[nsarray arraywithobject:sort]];     [corerequest setfetchbatchsize:20];     nsfetchedresultscontroller *controller = [[nsfetchedresultscontroller alloc] initwithfetchrequest:corerequest managedobjectcontext:self.managedobjectcontext sectionnamekeypath:nil cachename:@"root"];     self.results = controller;     self.results.delegate = self;     nserror *error;     [self.results performfetch:&error];      nsarray *fetchedobjects = [self.managedobjectcontext executefetchrequest:corerequest error:&error];     (nsmanagedobjectcontext *info in fetchedobjects)     {         self.orderstate = [nsstring stringwithformat:@"%@", [info valueforkey:@"id"]];          [self.namesarray addobject:[info valueforkey:@"title"]];         [self.quantityarray addobject:[info valueforkey:@"quantity"]];         [self.imagesarray addobject:[info valueforkey:@"thumbnail"]];         [self.pricearray addobject:[info valueforkey:@"price"]];         //nslog(@"list: %@", [info valueforkey:@"title"]);      }     if ([self.orderstate isequaltostring:@"1"])     {         self.confirmorderbutton.enabled = false;     }      //self.navigationcontroller.navigationitem.backbarbuttonitem.enabled = false;     //self.navigationitem.hidesbackbutton = yes;     // uncomment following line preserve selection between presentations.     // self.clearsselectiononviewwillappear = no;      // uncomment following line display edit button in navigation bar view controller.     // self.navigationitem.rightbarbuttonitem = self.editbuttonitem; }  - (void)didreceivememorywarning {     [super didreceivememorywarning];     // dispose of resources can recreated. }  #pragma mark - table view data source  - (nsinteger)numberofsectionsintableview:(uitableview *)tableview {     return 1; }  - (nsinteger)tableview:(uitableview *)tableview numberofrowsinsection:(nsinteger)section {     id sectioninfo = [[self.results sections] objectatindex:section];     return [sectioninfo numberofobjects]; }   - (uitableviewcell *)tableview:(uitableview *)tableview cellforrowatindexpath:(nsindexpath *)indexpath {     //uitableviewcell *cell = [tableview dequeuereusablecellwithidentifier:@"orderscell" forindexpath:indexpath];     vieworderscell *cell = [tableview dequeuereusablecellwithidentifier:@"orderscell" forindexpath:indexpath];      cell.title.text = [self.namesarray objectatindex:indexpath.row];     cell.thumbnail.image = [uiimage imagenamed:[self.imagesarray objectatindex:indexpath.row]];     cell.status.text = @"waiting confirm";      if ([self.orderstate isequaltostring:@"0"])     {         cell.status.text = @"waiting confirm";         cell.status.textcolor = [uicolor redcolor];     }      else     {         cell.status.textcolor = [uicolor greencolor];         cell.status.text = @"confirmed";     }      uilongpressgesturerecognizer *longpressrecognizer = [[uilongpressgesturerecognizer alloc] initwithtarget:self action:@selector(onlongpress:)];      [cell addgesturerecognizer:longpressrecognizer];     //cell.textlabel.text = [self.namesarray objectatindex:indexpath.row];     //cell.imageview.image = [uiimage imagenamed:[self.imagesarray objectatindex:indexpath.row]];     //cell.backgroundcolor = [uicolor clearcolor];      return cell; }    // override support conditional editing of table view. - (bool)tableview:(uitableview *)tableview caneditrowatindexpath:(nsindexpath *)indexpath {     return yes; }   // override support editing table view. - (void)tableview:(uitableview *)tableview commiteditingstyle:(uitableviewcelleditingstyle)editingstyle forrowatindexpath:(nsindexpath *)indexpath {     if (editingstyle == uitableviewcelleditingstyledelete)     {         // delete row data source          nsmanagedobject *managedobject = [self.results objectatindexpath:indexpath];         [self.managedobjectcontext deleteobject:managedobject];         [self.managedobjectcontext save:nil];          //[tableview deleterowsatindexpaths:@[indexpath] withrowanimation:uitableviewrowanimationfade];          //[tableview reloadrowsatindexpaths:@[indexpath] withrowanimation:uitableviewrowanimationfade];     } }  - (void)controllerwillchangecontent:(nsfetchedresultscontroller *)controller {     [self.tableview beginupdates]; }  - (void)controllerdidchangecontent:(nsfetchedresultscontroller *)controller {     [self.tableview endupdates]; }  - (void)controller:(nsfetchedresultscontroller *)controller didchangeobject:(id)anobject atindexpath:(nsindexpath *)indexpath forchangetype:(nsfetchedresultschangetype)type newindexpath:(nsindexpath *)newindexpath {     if (type == nsfetchedresultschangeinsert)     {         [self.tableview insertrowsatindexpaths:[nsarray arraywithobject:newindexpath] withrowanimation:uitableviewrowanimationfade];     }     if (type == nsfetchedresultschangedelete)     {         [self.tableview deleterowsatindexpaths:[nsarray arraywithobject:indexpath] withrowanimation:uitableviewrowanimationfade];     }     if (type == nsfetchedresultschangeupdate)     {      }     if (type == nsfetchedresultschangemove)     {         [self.tableview deleterowsatindexpaths:[nsarray arraywithobject:indexpath] withrowanimation:uitableviewrowanimationfade];         [self.tableview insertrowsatindexpaths:[nsarray arraywithobject:newindexpath] withrowanimation:uitableviewrowanimationfade];     } }  - (void)controller:(nsfetchedresultscontroller *)controller didchangesection:(id<nsfetchedresultssectioninfo>)sectioninfo atindex:(nsuinteger)sectionindex forchangetype:(nsfetchedresultschangetype)type {     if (type == nsfetchedresultschangeinsert)     {         [self.tableview insertsections:[nsindexset indexsetwithindex:sectionindex] withrowanimation:uitableviewrowanimationfade];     }     if (type == nsfetchedresultschangedelete)     {         [self.tableview deletesections:[nsindexset indexsetwithindex:sectionindex] withrowanimation:uitableviewrowanimationfade];     } }   /* // override support rearranging table view. - (void)tableview:(uitableview *)tableview moverowatindexpath:(nsindexpath *)fromindexpath toindexpath:(nsindexpath *)toindexpath { } */  /* // override support conditional rearranging of table view. - (bool)tableview:(uitableview *)tableview canmoverowatindexpath:(nsindexpath *)indexpath {     // return no if not want item re-orderable.     return yes; } */  #pragma mark - navigation  // in storyboard-based application, want little preparation before navigation - (void)prepareforsegue:(uistoryboardsegue *)segue sender:(id)sender {     // new view controller using [segue destinationviewcontroller].     // pass selected object new view controller. }  - (void)alertview:(uialertview *)alertview clickedbuttonatindex:(nsinteger)buttonindex {     if(buttonindex == 1 && alertview.tag == 1)     {         nslog(@"confirm pressed");         //////send order server//////          nsfetchrequest *fetchrequest = [nsfetchrequest fetchrequestwithentityname:@"order_list"];         nspredicate *predicate = [nspredicate predicatewithformat:@"id=0"];         fetchrequest.predicate = predicate;         nserror *error = nil;         nsarray *array = [self.managedobjectcontext executefetchrequest:fetchrequest error:&error];          (nsmanagedobjectcontext *info in array)         {             nsnumber *temp = [[nsnumber alloc] initwithint:1];             [info setvalue:temp forkey:@"id"];         }          [self.managedobjectcontext save:&error];          [self.tableview reloaddata];         self.confirmorderbutton.enabled = false;          [self.billalert show];     }      else if (buttonindex == 1 && alertview.tag == 2)     {         self.confirmorderbutton.enabled = true;         uialertview *billrequest = [[uialertview alloc] initwithtitle:@"bill request successful!" message:@"your bill has been requested successfully! waiter deliver possible! visiting bella italia!" delegate:self cancelbuttontitle:@"ok" otherbuttontitles:nil, nil];         billrequest.alertviewstyle = uialertviewstyledefault;         billrequest.tag = 3;         [billrequest show];          nsfetchrequest *fetchitems = [[nsfetchrequest alloc] init];         [fetchitems setentity:[nsentitydescription entityforname:@"order_list" inmanagedobjectcontext:self.managedobjectcontext]];         [fetchitems setincludespropertyvalues:no]; //only fetch managedobjectid          nserror *error = nil;         nsarray *array = [self.managedobjectcontext executefetchrequest:fetchitems error:&error];         [self.results performfetch:&error];         //error handling goes here          (nsmanagedobject *item in array)         {             [self.managedobjectcontext deleteobject:item];         }         nserror *saveerror = nil;         [self.managedobjectcontext save:&saveerror];     }      else if (buttonindex == 0 && alertview.tag == 2)     {      }      else if (buttonindex == 0 && alertview.tag == 3)     {         [self.navigationcontroller poptorootviewcontrolleranimated:uitableviewrowanimationfade];     } }  - (ibaction)confirmorder:(uibarbuttonitem *)sender {     nslog(@"confirm order");      uialertview *conforder = [[uialertview alloc] initwithtitle:@"confirm order!" message:@"this send order process. once done, no more changes available. sure want confirm order?" delegate:self cancelbuttontitle:@"cancel" otherbuttontitles:@"confirm", nil];     conforder.alertviewstyle = uialertviewstyledefault;     conforder.tag = 1;     [conforder show]; }  -(void)onlongpress:(uilongpressgesturerecognizer*)pgesture {     nslog(@"long press");     [self.billalert show];  } @end 

edit forgot mention using custom cell. maybe affects situation somehow? tried nslog variables store data supposed appear in tableview. data beeing passed, not appear in tableview. logically [self.tableview reloaddata in viewwillappear should trick, not........

i have similar setup in 1 apps , add observer viewcontroller table wants updating;

[[nsnotificationcenter defaultcenter] addobserver:self selector:@selector(reload) name:@"updatedcoredata" object:nil]; 

i clear arrays or dictionaries use in reload method , call (inside async queue);

[self.tableview performselectoronmainthread:@selector(reloaddata) withobject:nil waituntildone:no]; 

then when finish updating core data in other vc call it;

[[nsnotificationcenter defaultcenter] postnotificationname:@"updatedcoredata" object: nil]; 

and works fine me, don't know if @ all.

edit:

along lines of reload method;

- (void)reload {     // potential clean if neccesary      dispatch_queue_t queue = dispatch_get_global_queue(dispatch_queue_priority_default, 0);     dispatch_async(queue, ^{          // fetch core data & populate dictionaries/arrays          [self.tableview performselectoronmainthread:@selector(reloaddata) withobject:nil waituntildone:no];     }); } 

Comments

Popular posts from this blog

windows - Single EXE to Install Python Standalone Executable for Easy Distribution -

c# - Access objects in UserControl from MainWindow in WPF -

javascript - How to name a jQuery function to make a browser's back button work? -