Search code examples
objective-cnsarraynsdictionary

Accessing a dictionary entry in an array


Basically I have an array with 3 rows, each row is a NSDictionary with 6 elements (nameLabel, name, colorLabel, color, priceLabel, price).

Example:

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

Then I add those elements into an array:

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

And then I add them to a table with subviews.

I'm trying to write an alert, which is working, but written like this, it shows a whole row in between {}. (Ex: You selected {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];

Instead of that, I would like to only display the name of the selected element.

I realized I need to change this code segment, but don't know how to access the name element in the dictionary.

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

Solution

  • 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];