Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

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];

        }

        i++;
    }

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];