Josue Espinosa
Josue Espinosa

Reputation: 5089

NSSortDescriptor issues

I'm currently sorting through an entity called "Video". I'm trying to sort through all the videos first by the date recorded which is in the format "December 21, 2013", and then the title which is just a string. Here is the code i'm using:

- (void)viewWillAppear:(BOOL)animated {

    self.title = [NSString stringWithFormat:@"Videos of %@", _currentAthlete.full];

    AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    _managedObjectContext = [appDelegate managedObjectContext];
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    NSEntityDescription *video = [NSEntityDescription entityForName:@"Video" inManagedObjectContext:_managedObjectContext];
    [request setEntity:video];
    NSSortDescriptor *sortDescriptor =
    [[NSSortDescriptor alloc] initWithKey:@"date_recorded"
                                ascending:YES
                                 selector:@selector(localizedCaseInsensitiveCompare:)];
    NSSortDescriptor *sortDescriptor2 =
    [[NSSortDescriptor alloc] initWithKey:@"title"
                                ascending:YES
                                 selector:@selector(localizedCaseInsensitiveCompare:)];
    NSArray *sortDescriptors = [[NSArray alloc]initWithObjects:sortDescriptor, sortDescriptor2, nil];
    [request setSortDescriptors:sortDescriptors];

    NSError *error = nil;
    NSMutableArray *mutableFetchResults = [[_managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
    if (mutableFetchResults == nil) {
        //handle error
    }
    [self setVideoArray:mutableFetchResults];
    [self.tableView reloadData];

}

However, this is the order in which the table data appears:

Cell 1: Title @"Z", date recorded: @"December 14, 2013"
Cell 2: Title @"A", date recorded: @"December 21, 2013"
Cell 3: Title @"B", date recorded: @"December 7, 2013"
Cell 4: Title @"T", date recorded: @"December 8, 2013"

Am I doing something wrong? Any ideas why this is happening? If i'm doing this right, could it be something in cellForRowAtIndexPath?

Upvotes: 0

Views: 192

Answers (1)

tia
tia

Reputation: 9718

You sort them as a string, so the order is like that. If the date_recorded field type is a string, I think there is no easy way to make a query order by date value of a string field through Core Data, if there is even any.

You might consider changing your field type to date type, or order the data records after you have queried all the data from Core Data instead.

Upvotes: 1

Related Questions