简体   繁体   中英

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 context:@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 (ie 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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM