开发者

Loop through an array of dictionaries at cellForRowAtIndexPath

开发者 https://www.devze.com 2023-04-05 15:06 出处:网络
Ihave an array of dictionaries. Each dictionary has one category. I want to fill a tableview with all of the dictionaries with one category in common, which was selected in a previous tableview.

I have an array of dictionaries. Each dictionary has one category. I want to fill a tableview with all of the dictionaries with one category in common, which was selected in a previous tableview.

NSDictionary *name = [sortedNames objectAtIndex:indexPath.row];
NSMutableString *currentCat = [name objectForKey:@"category"];

if ([currentCat isEqualToString:catSelected]) {
    cell.textLabel.text = [name objectForKey:@"title"];
}

As you could've guessed, if the first two dictionaries in the ar开发者_StackOverflow中文版ray are not of the category selected type, but the third one is, then the third cellrow gets filled in.

How do I approach this the right way?


take a mutable array in .h file In viewWillAppear init and add objects for that array using your code like

  array = [[NSMutableArray alloc] init];
for(int i = 0;i<[sortedNames count];i++)
{
    NSDictionary *name = [sortedNames objectAtIndex:i];
    NSMutableString *currentCat = [name objectForKey:@"category"];

    if ([currentCat isEqualToString:catSelected]) {
        [array addObject:[name objectForKey:@"title"]];
    }
}

In numberOfRowsInSection method give

[array count];

In cellForRowAtIndexPath method

cell.textLabel.text =[array objectAtIndex:indexPath.row];


You could construct an NSMutableArray on loading your view controller. This array would only contain the objects you want to display in that table view.

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.namesArray = [NSMutableArray array];
    for (NSDictionary *dict in sortedNames) {
        if ([(NSString *)[dict objectForKey:@"category"] isEqualToString:catSelected]) {
            [newArray addObject:dict];
        }
    }
}


Then, in your tableView:cellForRowAtIndexPath:, you assign based on the index:

if (indexPath.row < [namesArray count]) {    // Just incase...
    cell.textLabel.text = [namesArray objectAtIndex:indexPath.row];
}

The key idea here is that we don't bring data we don't need for the table view.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号