Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.


Sorting an array based on attributes of an object

Hello all, I am trying to sort an NSMutableArray based on an NSUInteger attribute named baseRankNumber which is a part of the homeworkItem class. Here is the code, I don't understand what is wrong about it. Thank you!

    homeworkObject* homeworkItem = source.homeworkItem;
    NSUInteger* arrayLen = (NSUInteger*)[self.homeworkObjectItem count];

    for (NSUInteger* i = 0; i <arrayLen; i++) {

        homeworkObject* localHomeworkItem = [self.homeworkObjectItem objectAtIndex:*i];

        if (homeworkItem.baseRankNumber>localHomeworkItem.baseRankNumber) {

            [self.homeworkObjectItem replaceObjectAtIndex:*i withObject:homeworkItem];



3 Answers

Thomas Nilsen
Thomas Nilsen
14,957 Points

I think NSSortDiscriptor would be the right approach here. http://nshipster.com/nssortdescriptor/

Thank you Thomas!

Okay so I tried to sort the baseRankNumber proper of the homeworkItem object like this. Please note that delegate is the name of the appDelegate instance and not an actual delegate

NSSortDescriptor* baseRankDescriptor = [[NSSortDescriptor alloc] initWithKey:@"baseRankNumber" ascending:YES];

    NSArray *sortDescriptors = @[baseRankDescriptor];

    NSArray* sortedHomeworkItems = [self.delegate.homeworkItemsArray sortedArrayUsingDescriptors:sortDescriptors];

    [self.delegate.homeworkItemsArray removeAllObjects];

    [self.delegate.homeworkItemsArray arrayByAddingObjectsFromArray:sortedHomeworkItems];