Когда вы устанавливаете 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 ...
}