sorting NSMutableArray weird results with Core Data
I have been going over this for hours and cannot find the problem. I have an array of scores which I save at the end of a game in a core data model. After saving when I go back into the high scores viewcontroller I load the scores from core data and sort the array using the following function where scores array is an NSMutableArray with my 10 high scores
[self.scoresArray sortUsingFunction:firstNumSort c开发者_JS百科ontext:@selector(totalScore)];
//function to sort high scores in the array
NSInteger firstNumSort(id str1, id str2, void *context) {
static int counter = 0;
NSLog(@"counter = %d", counter);
counter++;
//NSLog(@"should be sorting");
int num1 = [str1 totalScore];
int num2 = [str2 totalScore];
if (num1 > num2) {
NSLog(@"%@ is greater than %@", num1, num2);
return NSOrderedAscending;
}
else if (num1 < num2){
NSLog(@"%@ is less than %@", num1, num2);
return NSOrderedDescending;
}
else {
NSLog(@"%@ is the same as %@", num1, num2);
return NSOrderedSame;
}
}
This always places the last score entry at the top of the list regardless of its value?? The stranger thing is that when I restart my app the same function puts all scores in correct descending order which is what I want, but obviously I dont want the user to have to restart the app to see the scores displayed in the correct order. Can anyone please shed some light on what is going on??
Many thanks
Jules
The only obvious problem I see with your code is that the context parameter you are passing to sortUsingFunction:context
(i.e. the @selector(totalScore)
) is not used by your function and could be replaced with NULL
. That wouldn't account for the behavior you are seeing though and is more a matter of style anyway. One other thing you might want to check is that the type of totalScore
in really an int
. Your NSLog
statements in the sort function are treating the as if they are objects (the %@
is the format specifier for an object, for and int you would use %d
.) Are you sure that total score is not actually NSString
or an NSNumber
? Other than that the sort function looks like it should work, and since you say that it does on start up, I would look outside of this code for the problem.
Have you verified, either in the debugger or via a NSLog
statement that the array is actually mis-sorted after the call? Perhaps there is some bug in how you are displaying the sorted scores or something is happening after the sort to change the order?
精彩评论