Search code examples
iphonearraysuitableviewdictionarycell

How to add dictionary inside of an array to UItableview using insertRowsAtIndexPaths?


How do I add the result of getnewdata to my existing tableView using insertRowsAtIndexPaths? I found several examples but cannot figure out.

- (void)getfirstdata {
     [...] //get JSON data
     self.data = jsonResult; //a dictionary inside of an array
     [self.tableView reloadData];
}

- (void)getnewdata {
     [...] //get new JSON data which has to be added to top of the table
     self.data = jsonnewResult; //a dictionary inside of an array
     [self.tableView reloadData];
}

(UITableViewCell *) tableView: (UITableView *) table_view cellForRowAtIndexPath: (NSIndexPath *) index_path
    static NSString *CellIdentifier = @"Cell";
    if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }
    id celldata = [self.data objectAtIndex:[index_path row]];
    cell.textLabel.text = [celldata valueForKeyPath:@"user.name"];
    cell.detailTextLabel.text = [celldata objectForKey:@"text"];

return cell;
}

Solution

  • For get new, you want to add to your data, so...

    - (void)getnewdata {
         [...] //get new JSON data which has to be added to top of the table
         [self.data addObjectsFromArray:jsonResult];
         [self.tableView reloadData];
    }
    

    Make sure self.data is an NSMutableArray.

    Edit

    It just occurred to me that you might want the new data on top....

    NSMutableArray *newModel = [NSMutableArray arrayWithArray:jsonResult];
    [newModel addObjectsFromArray:self.data];
    self.data = newModel;