Reputation: 845
Here is my code:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSInteger numberOfRowsPerSection = 0;
if (section == 0) {
for (int i = 0; i < [[[BNRItemStore sharedStore] allItems] count]; i ++) {
BNRItem *item = [[[BNRItemStore sharedStore] allItems] objectAtIndex:i];
if ([item valueInDollars] > 50) {
numberOfRowsPerSection ++;
}
}
}else{
for (int i = 0; i < [[[BNRItemStore sharedStore] allItems] count]; i ++) {
BNRItem *item = [[[BNRItemStore sharedStore] allItems] objectAtIndex:i];
if ([item valueInDollars] == 73) {
numberOfRowsPerSection ++;
}
}
}
return numberOfRowsPerSection;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"];
if (!cell) {
cell =[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"UITableViewCell"];
}
BNRItem *p = [[[BNRItemStore sharedStore] allItems] objectAtIndex:[indexPath row]];
if ([p valueInDollars] > 50 && indexPath.section == 0) {
[[cell textLabel] setText:[p description]];
}else if(indexPath.section == 1){
[[cell textLabel] setText:[p description]];
}
return cell;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 2;
}
I want to display in one section results > 50 and the other section the rest of the result but I don't know how to do it. I am getting duplicate results in each section.
Thanks
Upvotes: 0
Views: 1172
Reputation: 405
Your code doesn't reflect what you're describing ( > 50 and == 73 are kind of intersecting):
if (section == 0) {
for (int i = 0; i < [[[BNRItemStore sharedStore] allItems] count]; i ++) {
...
if ([item valueInDollars] > 50) {
...
}
}
}else{
for (int i = 0; i < [[[BNRItemStore sharedStore] allItems] count]; i ++) {
...
if ([item valueInDollars] == 73) {
...
}
}
}
And this line is incorrect too:
BNRItem *p = [[[BNRItemStore sharedStore] allItems] objectAtIndex:[indexPath row]];
because the indexPath.row will go with an indexPath.section (it means the row is relative to the section, not to the whole table). This is main cause of your problem having the same results for both sections.
Anyway, my suggestion for you is to perform a preprocessing step (maybe in viewDidLoad or somewhere else) to split your array into 2 arrays (one for each section) instead of using only one array for both sections.
Upvotes: 1
Reputation: 1061
If you are using a NSFetchedResultsController you can use the sectionNameKeyPath: argument to specify a "group-by" parameter. In your case you might just create a simple 0/1 property to your objects in the array.
[[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
managedObjectContext:_managedObjectContext
sectionNameKeyPath:@"threshold"
cacheName:@"Root"];
Upvotes: 0