当您在 中设置 UITableViewCell 时tableView:cellForRowAtIndexPath:
,您正在使用来自结果数组中某个索引的数据,基于单元格的索引路径。
执行您要求的最简单方法是使用所选单元格的索引路径并执行与上述相同的计算以找到该特定索引。然后你可以从原始数组中获取你需要的一切。看起来像这样:
- (NSUInteger)arrayIndexFromIndexPath:(NSIndexPath *)path {
// You could inline this, if you like.
return path.row;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)path {
NSUInteger index = [self arrayIndexFromIndexPath:path];
NSDictionary *data = [self.dataArray objectAtIndex:index];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:...];
if (!cell) {
cell = [[[UITableViewCell alloc] initWithStyle:... reuseIdentifier:...] autorelease];
}
// ... Set up cell ...
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)path {
NSUInteger index = [self arrayIndexFromIndexPath:path];
NSDictionary *data = [self.dataArray objectAtIndex:index];
// ... Do whatever you need with the data ...
}
一个稍微复杂(但可能更健壮)的方法是继承 UITableViewCell 以添加属性或 ivars 来保存您需要的数据;这可以像单个属性一样简单,以保存原始数组中的整个值。然后在选择方法中,您可以从单元格本身获取所需的所有内容。看起来像这样:
MyTableViewCell.h:
@interface MyTableViewCell : UITableViewCell {
NSDictionary *data_;
}
@property (nonatomic, retain) NSDictionary *data;
@end
MyTableViewCell.m:
@implementation MyTableViewCell
@synthesize data=data_;
- (void)dealloc {
[data_ release]; data_ = nil;
[super dealloc];
}
@end
接着:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)path {
NSUInteger index = [self arrayIndexFromIndexPath:path];
NSDictionary *data = [self.dataArray objectAtIndex:index];
// Remember, of course, to use a different reuseIdentifier for each different kind of cell.
MyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:...];
if (!cell) {
cell = [[[MyTableViewCell alloc] initWithStyle:... reuseIdentifier:...] autorelease];
}
cell.data = data;
// ... Set up cell ...
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)path {
MyTableViewCell *cell = [tableView cellForRowAtIndexPath:path];
NSDictionary *data = cell.data;
// ... Do whatever you need with the data ...
}