Selch
Selch

Reputation: 131

Cell title from dictionary

I have a table with 3 sections. I also have an array of dictionaries that I use for naming my cells, among other things. I want to populate my second section with items from my dictionary based on the favorite key.

This is what my dictionary looks like:

<array>
    <dict>
        <key>favorite</key>
        <string>NO</string>
        <key>title</key>
        <string>accessories.sku</string>
        <key>checkedState</key>
        <string>NO</string>
    </dict>
    <dict>
        <key>favorite</key>
        <string>YES</string>
        <key>title</key>
        <string>accessoriesImage</string>
        <key>checkedState</key>
        <string>NO</string>
    </dict>

I've iterated through this dictionary before for other things and I know I need to do that again but I can't quite grasp it for this case.

static NSString *kTitleKey = @"title";
static NSString *kCheckedState  = @"checkedState";
static NSString *kFavorite = @"favorite";

for (id dict in myArray]) {
    if ([dict[kFavorite] isEqualToString:@"YES"]) {
       cell.textLabel.text = [myArray objectAtIndex:[indexPath row] valueForKey:kTitleKey];
    }
}

But of course cell.textLabel.text = [myArray objectAtIndex:[indexPath row] valueForKey:kTitleKey] isn't correct.

Upvotes: 0

Views: 71

Answers (2)

arthankamal
arthankamal

Reputation: 6413

you are already matching your dictionary[kFavorite] then why you want to take it from myArray. you can code like this your loop,

for (id dict in myArray]) {
   if ([dict[kFavorite] isEqualToString:@"YES"]) {
      cell.textLabel.text = dict[kTitleKey];
   }
}

Upvotes: 1

Tim
Tim

Reputation: 226

You can just filter the array using NSPredicate, then drive the second section with the filtered array:

static NSString *kTitleKey = @"title";
static NSString *kCheckedState  = @"checkedState";
static NSString *kFavorite = @"favorite";

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%@ CONTAINS[c] %@", kFavorite, @"YES"];

NSArray *filteredArray = [myArray filteredArrayUsingPredicate:predicate];

Upvotes: 0

Related Questions