Core data: The fetched object at index x has an out of order section name 'xxxxxx. Objects must be sorted by section name

后端 未结 2 1979
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-05 06:43

I know I\'m not the first to ask this question but I\'m really stumped..

Basically I have a screen with two buttons. Each button loads data into a tableview below based

2条回答
  •  青春惊慌失措
    2021-02-05 06:54

    I also have got a similar issue, perhaps someone find it useful.

    I fetched financial transactions from DB and sectioned them by Month.

    DB has property trDate - which is a transaction date. But trMonth is a transient property like:

    - (NSString*)trMonth {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"LLLL"];
    [dateFormatter setLocale:[NSLocale currentLocale]];
    
    return [dateFormatter stringFromDate:trDate];
    }
    

    It was used in FetchResultsController like this:

    ...
    NSSortDescriptor *sortDate = [[NSSortDescriptor alloc] initWithKey:@"trDate" ascending:YES];
    
    [fetchRequest setSortDescriptors:@[sortDate]];
    
    NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:@"trMonth" cacheName:nil];
    ...
    

    Which worked well in production, but once app started to crash, and after discovering the root issue I figured out that there two transaction for (for instance) on July: July 2014 and July 2015. That was the crash point as trDate sorted well July 2014 < July 2015, but my method considered them as the same month. The solution was use as section names not only the month name but year also:

    - (NSString*)trMonthYear {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"LLLL yyyy"]; // added year also
    [dateFormatter setLocale:[NSLocale currentLocale]];
    
    return [dateFormatter stringFromDate:trDate];
    }
    

提交回复
热议问题