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
NAUSHAD DARUWALLA
1,587 PointsSorting NSMutableArray by using NSInteger property of an object
Hello all, I am trying to sort an NSMutableArray in descending order based on an NSInteger value of the object that is in the array. The object name is homeworkItem, the array name is homeworkObjectItem and the NSInteger that I'm trying to sort by is baseRankNumber. How would I do this? Thank you!
4 Answers
chriscameron
15,397 PointsNow, I haven't tried this out for myself, but rosettacode gives a snippet where you might be able to start. http://rosettacode.org/wiki/Sort_an_integer_array#Objective-C
NAUSHAD DARUWALLA
1,587 PointsBut this approach is for when you have used NSNumber and I have used NSInteger. How else can I do it and for NSInteger?
chriscameron
15,397 PointsOk so what have you got your NSInteger * "named" as?
Basically from what I've found, you may need to change the NSInteger to an NSNumber. The questioners code at the top does this, but remember to set your array. http://stackoverflow.com/questions/8600841/adding-nsinteger-object-to-nsmutablearray
NAUSHAD DARUWALLA
1,587 PointsOk so this is what i tried to sort the baseRankNumber property for each homeworkObject in the homeworkObjectItem array, but when I enter the second homework item, it crashes. What is wrong about this?
[self.homeworkObjectItem addObject:source.homeworkItem]; NSSortDescriptor *sortDescriptor; sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"baseRankNumber" ascending:YES]; NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor]; NSArray *sortedArray; sortedArray = [self.homeworkObjectItem sortedArrayUsingDescriptors:sortDescriptors]; [self.tableView reloadData];