unsupported NSSortDescriptor (comparator blocks are not supported)

淺唱寂寞╮ 提交于 2020-01-02 01:21:06

问题


In fetchedResultsController while setting the NSSortDescriptor iam getting this error unsupported NSSortDescriptor (comparator blocks are not supported).

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
                               entityForName:@"Alarm" inManagedObjectContext: managedObjectContext];
[fetchRequest setEntity:entity];

//Below code is not working and causing error. sorting use the hours&seconds part of the time attribute  

NSSortDescriptor *sort = [[NSSortDescriptor alloc]
                          initWithKey:@"time" ascending:YES comparator:^NSComparisonResult(id obj1, id obj2) {

                                  NSCalendar *calendar = [NSCalendar currentCalendar];
                                  NSDateComponents *components1 = [calendar components:(NSHourCalendarUnit|NSMinuteCalendarUnit) fromDate:obj1];
                                  NSDateComponents *components2 = [calendar components:(NSHourCalendarUnit|NSMinuteCalendarUnit) fromDate:obj2];
                                  NSDate *date1 = [calendar dateFromComponents:components1];
                                  NSDate *date2 = [calendar dateFromComponents:components2];


                                  return [date1 compare:date2];

                          }];

回答1:


You can't use sort descriptors with comparator blocks everywhere - for instance not with Core Data fetches.

They work fine when you filter normal arrays, though.

Apart from that - was there a question in there that I overlooked?




回答2:


As Monolo said, you can't use comparators block with Core Data. However, you can use:

[NSSortDescriptor sortDescriptorWithKey:(NSString *) ascending:(BOOL) selector:(SEL)]

You'll need to extend your model, if you aren't using a standard selector.

For example, I just needed to order strings "a la Finder" (i.e. 1,2,9,10, and not 1,10,2,9) and I used

request.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:myEntity ascending:NO selector:@selector(localizedStandardCompare:)]];

Take a look to the NSSortDescriptor Class Reference by Apple

Happy coding :)



来源:https://stackoverflow.com/questions/14938653/unsupported-nssortdescriptor-comparator-blocks-are-not-supported

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