开发者

NSFetchedResultsController - how does sectionNameForKeypath get its data?

开发者 https://www.devze.com 2023-02-18 19:40 出处:网络
I\'ve been having a few nightmares with NSFetchedResultsController and in trying to 开发者_如何学JAVAfind a solution to my problem outlined here, I came across something unusual about the data being f

I've been having a few nightmares with NSFetchedResultsController and in trying to 开发者_如何学JAVAfind a solution to my problem outlined here, I came across something unusual about the data being fetched by a fetchedResultsController, particularly the sectionNameForKeypath parameter.

Suppose I have an object model with 2 Entities and relationships as per below:

Item <<--> Category

Category has an (NSNumber*) attribute called displayOrder which is used to separate the fetched Item instances into sections in a table view:

NSFetchedResultsController *controller = [[NSFetchedResultsController alloc]
                                          initWithFetchRequest:fetchRequest
                                          managedObjectContext:moc
                                          sectionNameKeyPath:@"category.displayOrder"
                                          cacheName:nil];

If I wanted to somehow manipulate the output of displayOrder dynamically, the obvious choice would be to overwrite its getter method and do whatever I want in there. But the problem is, the getter for displayOrder is never accessed during the fetchRequest or by the fetchedResultsController at all, even though I am specifying it in the sectionNameForKeypath, AND I can see the fetchedResultsController is using its values to separate and display the sections.

Here's a simple example of an overwritten getter method which never gets called. This was placed inside my Category class:

-(NSNumber*)displayOrder
{
    NSLog (@"displayOrder getter called");
    NSNumber *displayOrder = [NSNumber numberWithInt:0];
    return displayOrder;
}

I've also tried overwriting awakeFromFetch to no avail (also doesn't get called, but that doesn't surprise me as I'm fetching Item instances and accessing the category and its attributes through the relationships).

So finally my question is: how does the category.displayOrder values get passed to my fetchedResultsController and is there a way for me to control this output?

Thanks in advance for any ideas you may have!

Rog


Since iOS 3.2, NSFetchedResultsController uses the field identified by sectionNameKeyPath directly from the database whenever possible, rather than creating objects for every item. You could try using a non-persistent property for the sectionNameKeyPath, which (according to the documentation) would force it to create the objects, but if it's just a matter of renaming the sections for a UITableView it would be better to do the mapping in tableView:titleForHeaderInSection:.

0

精彩评论

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

关注公众号