简体   繁体   中英

How to have UITableViewCell reference objects in an array?

I have an array of objects that have multiple instance variables ( name , address , number , etc). I also have a UITableViewController whose table view is populated with the name variable of each of these objects.

I have also created a DetailViewController that should display the rest of the information held by these objects when that objects' designated cell is selected with tableView:didSelectRowAtIndexPath: . The problem is, these cells only have references to the cell's objects' name variable.

How should I go about fixing this problem? Would I need to subclass the cell so that I could give each cell a reference to the entire object? or is there an easier way?

This is my current tableView:cellForRowAtIndexPath: method:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if(!cell){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];
    }
    cell.textLabel.text = [[listings objectAtIndex:indexPath.row] objectForKey:@"listingName"];
    return cell;
}

update: it just occured to me that I could grab the row number from indexPath and grab the designated object from the array. Would this be more viable?

In tableView:didSelectRowAtIndexPath: you can just use [listings objectAtIndex:indexPath.row] to get the selected object, and pass that to the detail view controller.

(You should never try to use the table view cells as data source.)

Since you are displaying the listings directly from their array position, you get them out again the same way once you pressed the row.

In tableView:didSelectRowAtIndexPath: just do [listings objectAtIndex:indexPath.row] to get the object in question and send it over to the DetailViewController

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM