访问数组中的字典条目

时间:2013-06-19 10:01:53

标签: objective-c nsarray nsdictionary

基本上我有一个包含3行的数组,每行是一个带有6个元素的NSDictionary(nameLabel,name,colorLabel,color,priceLabel,price)。

示例:

NSDictionary* row1 = [[NSDictionary alloc]
initWithObjectsAndKeys:@"MacBook",@"Name",@"White",@"Color",@"$1200",@"Price", nil];

然后我将这些元素添加到数组中:

NSArray* array = [[NSArray alloc] initWithObjects:row1,row2,row3, nil];
//row2 and row3 being the same as row1 but with different strings.

然后我将它们添加到带有子视图的表中。

我正在尝试编写一个正在运行的警报,但是这样编写,它在{}之间显示了整行。 (例如:您选择了{Color = Black; Name = iPhone; Price = $ 600;}。

NSUInteger row = [indexPath row];
NSString *rowValue = [computers objectAtIndex:row];
NSString *message = [[NSString alloc] initWithFormat:
                     @"You selected %@", rowValue];
UIAlertView *alert = [[UIAlertView alloc]
                      initWithTitle:@"Row Selected!"
                      message:message
                      delegate:nil
                      cancelButtonTitle:@"No"
                      otherButtonTitles:nil];
[alert show];

而不是那样,我只想显示所选元素的名称。

我意识到我需要更改此代码段,但不知道如何访问字典中的name元素。

NSString *message = [[NSString alloc] initWithFormat:
                     @"You selected %@", rowValue];

1 个答案:

答案 0 :(得分:0)

NSUInteger row = [indexPath row];
NSDictionary *dictionary = [array objectAtIndex:row]; 
NSString *name = [dictionary objectForKey:@"Name"];
NSString *message = [[NSString alloc] initWithFormat:@"You selected %@",name];
UIAlertView *alert = [[UIAlertView alloc]
                      initWithTitle:@"Row Selected!"
                      message:message
                      delegate:nil
                      cancelButtonTitle:@"No"
                      otherButtonTitles:nil];
[alert show];