Showing duplicate cells in UITableView via NSFetchedResultsController?

孤者浪人 提交于 2019-12-10 12:19:30

问题


I am querying Core Data to find the "OLDEST" and "HEAVIEST" amongst a group of people. With a larger dataset this usually works (as the chance of a duplicate match is less), but with a small dataset where the OLDEST person may also be the HEAVIEST I am having problems.

[John, 77, 160]
[Pete, 56, 155]
[Jane, 19, 130]
[Fred, 27, 159]
[Jill, 32, 128]

As I want to display this information in 2 UITableViewCells of a UITableView I am doing this by first running 2 NSFetchRequests (one to find the OLDEST, the second to find the HEAVIEST) I am them taking the objectIDs for each managed object and adding them to a final NSFetchRequest that I am using to setup my NSFetchedResultsController.

// FETCH REQUEST - OLDEST, HEAVIEST
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"People"];
NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:@"age" ascending:YES];
[fetchRequest setSortDescriptors:[NSArray arrayWithObject:descriptor]];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF IN %@", IDArray];
[fetchRequest setPredicate:predicate];

If I "Print the Description" of the final NSFetchRequest it does indeed contain 2 pointers to managedObjects.

(i.e. [John, 77, 160] [John, 77, 160])

My problem seems to be that when I do

[[self fetchedResultsController] performFetch:nil];

the UITableView delegate method:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSArray *sectionArray = [[self fetchedResultsController] sections];
    id <NSFetchedResultsSectionInfo> sectionInfo = [sectionArray objectAtIndex:0];
    NSUInteger numberOfRows = [sectionInfo numberOfObjects];
    NSLog(@"ROWS: %u", numberOfRows);
    return numberOfRows;
}

only shows the numberOfRows as 1 and only displays a single [John, 77, 160] in my UITableView.


回答1:


A fetch request does not return duplicate objects. It returns all objects that match the predicate. So

[NSPredicate predicateWithFormat: @"objectID = %@", oid]
[NSPredicate predicateWithFormat: @"(objectID = %@) OR (objectID = %@)", oid, oid]
[NSPredicate predicateWithFormat: @"objectID IN %@", @[oid, oid]]

return all one object with the given object ID (if there is one).

In your case, you have already the objects that you want to display. Therefore I would suggest to store them in an array and use that as table view data source, instead of using a fetched results controller.



来源:https://stackoverflow.com/questions/15523234/showing-duplicate-cells-in-uitableview-via-nsfetchedresultscontroller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!