NSSortDescriptor неправильно сортирует целые числа

Я пытаюсь отсортировать по дате, а затем по времени начала. Время начала – минуты от полуночи. Поэтому, если время начала равно ‹ 100, оно не будет сортироваться должным образом.

- (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;
}

Как я могу правильно отсортировать целые числа?


person Bot    schedule 27.03.2012    source источник
comment
Я надеюсь, ваше start_time (в вашей объектной модели Core Data) является объектом NSNumber, а не строкой.   -  person Michael Dautermann    schedule 28.03.2012


Ответы (1)


Если start_time является строкой, то она будет отсортирована в алфавитном порядке, что означает, что aa предшествует b, что также означает, что 11 предшествует 2.

Чтобы сортировать более удобным для человека способом, используйте localizedStandardCompare: NSString в качестве селектора.

[NSSortDescriptor sortDescriptorWithKey:@"start_time" ascending:YES selector:@selector(localizedStandardCompare:)]
person Nathan Kinsinger    schedule 28.03.2012
comment
Вот оно! Благодарю. Я храню его в своих основных данных в виде строки, потому что он поступает из API в виде строки, а не числа. - person Bot; 28.03.2012
comment
это круто. именно то, что я искал. У меня была проблема, что мой строковый столбец был отсортирован таким образом 1,10,11,2,3,4... выше решение решило это. - person shaikh; 18.02.2013
comment
NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:@dateTimeInSec по возрастанию:YES selector:@selector(localizedStandardCompare:)]; разбил мое приложение. Является ли start_time атрибутом типа NSString или NSNumber? Ошибка: [__NSCFNumber localizedStandardCompare:]: нераспознанный селектор отправлен экземпляру 0x16dc40c0 с userInfo (null) - person coolcool1994; 26.12.2013