问题
I have problem with my sort descriptor. I am fetching a ranking of a football club. This is how my webservice gives the data back.
"ranking": [
{
"type": "competitie",
"position": "1",
"name": "Club Brugge",
"gamesPlayed": "10",
"gamesWon": "6",
"gamesTied": "4",
"gamesLost": "0",
"goalsPos": "25",
"goalsNeg": "12",
"goalsDiff": 13,
"points": "22"
}
Here is my fetch request.
- (void)getKlassement // attaches an NSFetchRequest to this UITableViewController
{
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Klassement"];
request.sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"position" ascending:YES]];
self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request
managedObjectContext:self.genkDatabase.managedObjectContext
sectionNameKeyPath:nil
cacheName:nil];
}
Now the ranking is the following. 1,11,12,13,14,2,3,4,5... I think the problem is that position is a String in my webservice. And my sort descriptor is looking at it as a string. But actually it should look at it as an integer. Does anybody knows how I can do this ?
Thanks in advance.
回答1:
Even if the "position" is provided as a string from your web service, the best solution would be to store it as number ("Integer 32" or similar) in the Core Data model. The corresponding property of the object will be NSNumber
and it will be sorted correctly.
If you really cannot go this way, you could as a workaround try to use localizedStandardCompare
as comparison function. I think that sorts strings containing numbers according to their numeric values.
[NSSortDescriptor sortDescriptorWithKey:@"position" ascending:YES
selector:@selector(localizedStandardCompare:)]
来源:https://stackoverflow.com/questions/12782997/working-with-fetched-request-sort-descriptors