如何通过选择tableview单元获取字典值?

时间:2014-05-16 15:49:37

标签: ios objective-c arrays uitableview dictionary

我有两个数组和一个字典,其中包含ViewDidLoad方法中显示的数字和国家/地区。 当用户单击特定单元格时,该国家/地区将显示在控制台中。 我怎样才能做到这一点。 提前谢谢。

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
arrayofNumbers = [[NSArray alloc] initWithObjects:@"1",@"2",@"3",@"4",@"5", nil];

arrayofCountries = [[NSArray alloc]initWithObjects:@"India",              @"America",@"Pakistan",@"Germany",@"Australia",nil];

dictOfCountries = [[NSDictionary alloc] initWithObjects:arrayofNumbers   forKeys:arrayofCountries];

}

-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath   *)indexPath
{ 
    NSIndexPath *selectedIndexPath = [tableView indexPathForSelectedRow];
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:selectedIndexPath];
    NSLog(@"%@", cell.textLabel.text);
}

2 个答案:

答案 0 :(得分:0)

-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath   *)indexPath { 

    NSLog(@"%@", arrayOfCountries[indexPath.row]);
}

答案 1 :(得分:0)

为什么要创建NSDictionary和额外NSArray来保存indexPath?您可以通过arrayofCountries数组中的索引访问所选国家/地区。

viewDidLoad方法更改为:

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
arrayofCountries = [[NSArray alloc]initWithObjects:@"India",@"America",@"Pakistan",@"Germany",@"Australia",nil];
}

并实施didSelectRowAtIndexPath委托方法如下

-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath   *)indexPath { 

// when user select a cell in your tableView the indexPath of this cell is the
// index of your dataSource array in  your case this is arrayOfCountries 

    NSLog(@"Selected Country ----> %@", [arrayOfCountries objectAtIndex:[indexPath.row]]);
}