iPhone SDK-选择了UITableViewCell时,在UITableViewCell中未显示的数组中传递数据

| 我已经在各处搜索了教程或可以向我展示如何从填充单元格cell.textlabel.text字段的数组中传递数据的东西,该字段在该节点中也有其他信息... 为简单起见,我从正在生成XML文件的Web服务中提取数据。返回一个“ ID”,“名称”,“ OtherID”字段。然后,使用已解析的XML填充UITableViewController,本质上仅是cell.textLabel.text的\“ Name \”字段。我有所有的工作。 但是,我现在需要做的是: 当用户确实选择一行时,我需要将\“ ID \”和\“ OtherID \”字段(在单元格中未显示)设置为变量,切换视图,并使用以下命令设置新视图的UILabel旧视图中的变量。 这就是我不知所措的地方... 有人能指出我该如何完成此代码的教程或代码示例的方向吗?或者,如果您与我有类似的分享? 非常感谢您的参与!     
已邀请:
在ѭ0中设置UITableViewCell时,您正在使用基于单元格索引路径的结果数组中某个索引的数据。 执行要求的最简单方法是使用选定单元格的索引路径,并执行与上述相同的计算以找到该特定索引。然后,您可以从原始数组中获取所需的一切。看起来像这样:
- (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 ...
}
    

要回复问题请先登录注册