1

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.

Matteo
  • 14,696
  • 9
  • 68
  • 106
Lion
  • 872
  • 1
  • 17
  • 43

3 Answers3

2

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

Nishant Tyagi
  • 9,893
  • 3
  • 40
  • 61
Rahul Sharma
  • 3,013
  • 1
  • 20
  • 47
  • Ok- Rahul. first I'll check this, if work then I'll accept your answer. Thanks – Lion Sep 14 '11 at 10:19
  • No issues Lion.. Meanwhile if you come across any good approach that saves time do share with all of us.. Happy coding – Rahul Sharma Sep 14 '11 at 10:41
  • *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayM studentRank]: unrecognized selector sent to instance 0x69ad7d0'. In this Line NSLog(@"arrGroupedStudents name - %@ rank - %@",object.studentName, object.studentRank); – Lion Sep 14 '11 at 10:41
  • It means you are trying to access studentRank from an object which is an array and not an object of TopStudents class. Try debug mode and see where the application gets crashed. – Rahul Sharma Sep 14 '11 at 10:44
  • What is the type of object in NSLog(@"arrGroupedStudents name - %@ rank - %@",object.studentName, object.studentRank); – Rahul Sharma Sep 14 '11 at 10:54
  • NSString *studentName, *studentRank; – Lion Sep 14 '11 at 10:57
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/3437/discussion-between-lion-and-rahul-sharma) – Lion Sep 14 '11 at 10:57
1

If you want to display in the order of ranks, you should set the ascending as YES.

NSSortDescriptor * sortByRank = [[NSSortDescriptor alloc] initWithKey:@"studentRank" ascending:YES];
visakh7
  • 26,380
  • 8
  • 55
  • 69
0
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];
}
klefevre
  • 8,595
  • 7
  • 42
  • 71