Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unsupported NSSortDescriptor (comparator blocks are not supported)

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];

                          }];
like image 945
Anil Varghese Avatar asked Feb 18 '13 14:02

Anil Varghese


2 Answers

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?

like image 162
Monolo Avatar answered Sep 30 '22 13:09

Monolo


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 :)

like image 43
Bruno Belotti Avatar answered Sep 30 '22 13:09

Bruno Belotti