NSSortDescriptor does not sort integers correctly

I try to sort by date and then start the time. Start time - minutes from midnight. Therefore, if the start time is <100, it will not be sorted correctly.

- (NSFetchedResultsController *)fetchedResultsController { if (fetchedResultsController != nil) { return fetchedResultsController; } /* Set up the fetched results controller. */ // Create the fetch request for the entity. NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; // Edit the entity name as appropriate. NSEntityDescription *entity = [NSEntityDescription entityForName:@"Appointments" inManagedObjectContext:[[DataManager sharedInstance] managedObjectContext]]; [fetchRequest setEntity:entity]; [fetchRequest setIncludesPendingChanges:YES]; // Set the batch size to a suitable number. //[fetchRequest setFetchBatchSize:20]; // Sort using the date / then time property. NSSortDescriptor *sortDescriptorDate = [[NSSortDescriptor alloc] initWithKey:@"date" ascending:YES]; NSSortDescriptor *sortDescriptorTime = [[NSSortDescriptor alloc] initWithKey:@"start_time" ascending:YES]; NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptorDate, sortDescriptorTime, nil]; [fetchRequest setSortDescriptors:sortDescriptors]; // Use the sectionIdentifier property to group into sections. NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:[[DataManager sharedInstance] managedObjectContext] sectionNameKeyPath:@"date" cacheName:@"List"]; aFetchedResultsController.delegate = self; self.fetchedResultsController = aFetchedResultsController; NSLog(@"FetchedController: %@", fetchedResultsController); return fetchedResultsController; } 

How can I correctly execute these integers?

+6
source share
1 answer

If start_time is a string, it will be sorted alphabetically, which means aa to b , which also means that 11 is before 2 .

To sort in a more human-friendly way, use NSString localizedStandardCompare: as a selector.

 [NSSortDescriptor sortDescriptorWithKey:@"start_time" ascending:YES selector:@selector(localizedStandardCompare:)] 
+27
source

Source: https://habr.com/ru/post/911809/


All Articles