Friday, March 26, 2010

Fetched List Controller, sections and categories

I was creating a fetched list controller, and my predicate did not sort by the category.  I found that I got a lot of errors in my log file when I fetched data.  In particular I was using a 'nil' predicate to fetch all data.

2010-03-27 00:12:50.173 SightWordsUnlimited[18877:207] NSFetchedResultsController ERROR: object Fry First 20009 returned nil value for section name key path 'Category'. Object will be placed in unnamed section
2010-03-27 00:12:50.174 SightWordsUnlimited[18877:207] NSFetchedResultsController ERROR: object Hi returned nil value for section name key path 'Category'. Object will be placed in unnamed section
2010-03-27 00:12:50.175 SightWordsUnlimited[18877:207] NSFetchedResultsController ERROR: object Test99 returned nil value for section name key path 'Category'. Object will be placed in unnamed section
2010-03-27 00:12:50.176 SightWordsUnlimited[18877:207] NSFetchedResultsController ERROR: The fetched object at index 6 has an out of order section name '. Objects must be sorted by section name'



In addition when I went to another dialog, and changed the managed context the fetched object controller was using, the mismatched sections caused a 'Bad Access Exception'.
The error I received was:


*** -[_NSDefaultSectionInfo sectionOffset]: message sent to deallocated instance 0x3b41d10




I put a quick fix in, in my JLFetchedControllerSource I modified the fetch so that if a section field is present, sort by that prior to sorting by the key.  I think the code is a little ugly but it seems to work.




NSSortDescriptor *catSort=nil;
if (self.sectionField!=nil)
catSort=[[NSSortDescriptor alloc] initWithKey:self.sectionField ascending:YES];
NSSortDescriptor *keysortDesc=[[NSSortDescriptor alloc] initWithKey:sortField ascending:YES];
NSSortDescriptor *first=keysortDesc;
NSSortDescriptor *second=nil;
if (catSort!=nil)
{
first=catSort;
second=keysortDesc;
}
NSArray *sortDescs=[[NSArray alloc] initWithObjects:first,second,nil];

No comments:

Post a Comment