Segev
Segev

Reputation: 19303

Filling TableView sections with data ??

I have a dictionaries inside an array that includes properties such as name, pic and day (the day is just a string from a picker view).

I want to show a weekly table view and arrange the items by the day.

What I'm planing on doing is to create a new array for every day, filter all my data into those arrays and then populate the sections. Is there a smarter way doing that?

I can't think of another way to get numberOfRowsInSection if i don't filter my data first.

Upvotes: 2

Views: 278

Answers (1)

Tim
Tim

Reputation: 60130

The other way to do this is to filter your array of dictionaries live every time you need to return a value for -tableView:numberOfRowsInSection:. You would

  • Figure out what day corresponds to the requested section, then
  • Filter your array of dictionaries based on that day and return a count

Some code (not compiled, not tested) to do this might look something like:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSString *day = [self _dayForTableViewSection:section]; // assuming this exists
    NSPredicate *filter = [NSPredicate predicateWithBlock:^(id obj, NSDictionary *bindings) {
        assert([obj isKindOfClass:[NSDictionary class]]); // array contains dictionaries
        return [obj[@"day"] isEqualToString:day]; // assuming key is @"day"
    }];
    NSArray *matchingDictionaries = [self.allDictionaries filteredArrayUsingPredicate:filter]; // assuming data source is allDictionaries
    return matchingDictionaries.count;
}

Depending on how frequently your code calls -tableView:numberOfRowsInSection: and the size of your complete data source, this could incur a fairly serious performance hit. You might be better off doing what you originally suggest: filter the data ahead of time and keep appropriate arrays up to date for use in your table view. (Though remember that premature optimization can often do more harm than good!)

Upvotes: 1

Related Questions