简体   繁体   English

如何在数组中具有UITableViewCell引用对象?

[英]How to have UITableViewCell reference objects in an array?

I have an array of objects that have multiple instance variables ( name , address , number , etc). 我有一个具有多个实例变量( nameaddressnumber等)的对象数组。 I also have a UITableViewController whose table view is populated with the name variable of each of these objects. 我还有一个UITableViewController其表视图中填充了每个对象的name变量。

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: . 我还创建了一个DetailViewController ,当使用tableView:didSelectRowAtIndexPath:选择对象的指定单元格时,应显示这些对象保留的其余信息。 The problem is, these cells only have references to the cell's objects' name variable. 问题是,这些单元格仅引用该单元格对象的name变量。

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: 这是我当前的tableView:cellForRowAtIndexPath:方法:

- (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. 更新:我只是想到我可以从indexPath获取行号,并从数组中获取指定的对象。 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. tableView:didSelectRowAtIndexPath:您可以仅使用[listings objectAtIndex:indexPath.row]来获取所选对象,并将其传递给详细视图控制器。

(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 tableView:didSelectRowAtIndexPath:只需执行[listings objectAtIndex:indexPath.row]以获取有问题的对象并将其发送到DetailViewController

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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