简体   繁体   中英

How to sort NSMutableArray elements?

I have model class which contains NSString's- studentName , studentRank and studentImage . I wanna sort the NSMutableArray according to studentRanks . what I have done is

- (void)uploadFinished:(ASIHTTPRequest *)theRequest
{
    NSString *response = nil;
    response = [formDataRequest responseString];
    NSError *jsonError = nil;
    SBJsonParser *json = [[SBJsonParser new] autorelease];
    NSArray *arrResponse = (NSArray *)[json objectWithString:response error:&jsonError];
    if ([jsonError code]==0) {
        // get the array of "results" from the feed and cast to NSArray
        NSMutableArray *localObjects = [[[NSMutableArray alloc] init] autorelease];
        // loop over all the results objects and print their names
        int ndx;

        for (ndx = 0; ndx < arrResponse.count; ndx++) 
        {
            [localObjects addObject:(NSDictionary *)[arrResponse objectAtIndex:ndx]];
        }

        for (int x=0; x<[localObjects count]; x++) 
        {
            TopStudents *object = [[[TopStudents alloc] initWithjsonResultDictionary:[localObjects objectAtIndex:x]] autorelease];

            [localObjects replaceObjectAtIndex:x withObject:object];
        }

        topStudentsArray = [[NSMutableArray alloc] initWithArray:localObjects];

    }
}

How can I sort this topStudentsArray according to the ranks scored by the Students and If the two or more student have the same rank, How can I group them. I did like this

TopStudents *object;
    NSSortDescriptor * sortByRank = [[[NSSortDescriptor alloc] initWithKey:@"studentRank" ascending:NO] autorelease];
    NSArray * descriptors = [NSArray arrayWithObject:sortByRank];
    NSArray * sorted = [topStudentsArray sortedArrayUsingDescriptors:descriptors];

but this is not displaying results properly. please help me to overcome this problem. thanks in advance.

doing something like this might do the trick

Initially sort the arrGroupedStudents in the (ascending/descending) order of studentRank

//Create an array to hold groups
NSMutableArray* arrGroupedStudents = [[NSMutableArray alloc] initWithCapacity:[topStudentsArray count]];

for (int i = 0; i < [topStudentsArray count]; i++) 
{
    //Grab first student
    TopStudents* firstStudent = [topStudentsArray objectAtIndex:i];

    //Create an array and add first student in this array
    NSMutableArray* currentGroupArray = [[[NSMutableArray alloc] initWithCapacity:0] autorelease];
    [currentGroupArray addObject:firstStudent];

    //create a Flag and set to NO
    BOOL flag = NO;
    for (int j = i+1; j < [topStudentsArray count]; j++) 
    {
        //Grab next student
        TopStudents* nextStudent = [topStudentsArray objectAtIndex:j];  

        //Compare the ranks
        if ([firstStudent.studentRank intValue] == [nextStudent.studentRank intValue]) 
        {
            //if they match add this to same group
            [currentGroupArray addObject:nextStudent];
        }
        else {
            //we have got our group so stop next iterations
            [arrGroupedStudents addObject:currentGroupArray];
                           // We will assign j-1 to i
            i=j-1;
            flag = YES;
            break;
        }
    }
    //if entire array has students with same rank we need to add it to grouped array in the end
    if (!flag) {
        [arrGroupedStudents addObject:currentGroupArray];
    }
}

Finally your arrGroupedStudents will contain grouped array with equal rank. I have not test run the code so you might need to fix a few things falling out of place. Hope it helps

如果要按等级顺序显示,则应将ascending设置为YES

NSSortDescriptor * sortByRank = [[NSSortDescriptor alloc] initWithKey:@"studentRank" ascending:YES];
static int mySortFunc(NSDictionary *dico1, NSDictionary *dico2, void *context)
{
    NSString *studentName1 = [dico1 objectForKey:@"studentName"];
    NSString *studentName2 = [dico2 objectForKey:@"studentName"];
    return [studentName1 compare:studentName2];
}

- (IBAction)sortBtnTouched:(id)sender
{
    [topStudentsArray sortUsingFunction:mySortFunc context:NULL];
}

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