Reputation: 854
So I have a Core Data entity which I am trying to display in a table view using an NSFetchedResultsController. The relevant model attributes looks something like this:
Post
The relations form a tree with the root Post being the one where parentPost = nil. The way I want this to display is that every root post is the first item in a section and then the rest of the rows are a flattened list of the children of the root.
This is easy enough to arrange manually by doing a fetch request like this:
let fetchRequest = NSFetchRequest(entityName: Post.entityName())
fetchRequest.predicate = NSPredicate(format: "parentPost = NULL")
fetchRequest.sortDescriptors = sortOrder.sortDescriptors
fetchRequest.fetchBatchSize = 20
fetchRequest.relationshipKeyPathsForPrefetching = ["allChildren"]
Then I can build the section array from each of the results doing something like this:
let sectionPost = self.fetchedResultsController!.fetchedObjects![section] as! Post
var sectionArray = NSMutableArray(object: sectionPost)
var filteredSet = sectionPost.allChildren.filteredOrderedSetUsingPredicate(NSPredicate(format: "approved != FALSE AND postDeleted != TRUE AND spam != TRUE"))
sectionArray.addObjectsFromArray(filteredSet.array)
The question is: is there a way to do this all within the FRC? Maintaining a separate datasource from the FRC is complicated and I'd rather find a way to do this with a single fetch request but I don't see a great way of handling this.
Upvotes: 1
Views: 306
Reputation: 50129
no the grouping must happen on a key on the entity. so use a transient property or a fetched property to get the relation and make it a key
in your case.. e.g. make all POST objects have a key 'postToGroupBy' or 'postNameToGroupBy or whatever so the post and all its children are in the same group
Upvotes: 1