-1

So I have a person mutablearray where each object contains 3 NSString properties: firstName, lastName and age. I'd like to know how to sort these objects so it's arranged alphabetically by lastName so that I can display that in a table view (and make edits to it later by clicking on the name). Everything else is set up fine, just not the way the names are displayed in the table.

I've tried using

[self.person sortedArrayUsingSelector@selector(caseInsensitiveCompare:)];

but this returns the error: unrecognized selector sent to instance.
All help is appreciated :)


Solved it by using:

NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"lastName" ascending:YES];
[self.person sortUsingDescriptors:[NSArray arrayWithObject:sort]];

Thanks all for the input :)

vikingosegundo
  • 52,040
  • 14
  • 137
  • 178
Julia
  • 65
  • 1
  • 1
  • 9
  • possible duplicate of [How to sort an NSMutableArray with custom objects in it?](http://stackoverflow.com/questions/805547/how-to-sort-an-nsmutablearray-with-custom-objects-in-it) – vikingosegundo Apr 04 '14 at 03:56
  • you don't call sort method on the property you want to sort on. you call them on arrays containing the objects you ant to sort. – vikingosegundo Apr 04 '14 at 04:00

2 Answers2

1

You need to implement a comparison method in your person class if you want to use selector, something like this.

- (NSComparisonResult)compare:(Person *)otherObject {
  return [self.lastName compare:otherObject.lastName ];
}

NSArray *sortedArray;
sortedArray = [unSortedArray sortedArrayUsingSelector:@selector(compare:)];

This Stackoverflow question explains further methods that may be used as well.

Community
  • 1
  • 1
James Kidd
  • 444
  • 4
  • 8
1

You'd want to use sortedArrayUsingComparator: instead:

array = [array sortedArrayUsingComparator: ^(id a, id b) {
            NSString *first = [a objectForKey:@"lastName"];
            NSString *second = [b objectForKey:@"lastName"];
            return [first compare:second];
        }];

Note that I'm not on a mac right now and this is typed by hand, there may be small errors

vikingosegundo
  • 52,040
  • 14
  • 137
  • 178
mspensieri
  • 3,501
  • 15
  • 18