Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting an array of Objective-c objects

So I have a custom class Foo that has a number of members:

@interface Foo : NSObject {
    NSString *title;
    BOOL     taken;
    NSDate   *dateCreated;
}

And in another class I have an NSMutableArray containing a list of these objects. I would very much like to sort this array based on the dateCreated property; I understand I could write my own sorter for this (iterate the array and rearrange based on the date) but I was wondering if there was a proper Objective-C way of achieving this?

Some sort of sorting mechanism where I can provide the member variable to sort by would be great.

In C++ I used to overload the < = > operators and this allowed me to sort by object, but I have a funny feeling Objective-C might offer a nicer alternative?

Many thanks

like image 275
davbryn Avatar asked May 06 '10 11:05

davbryn


People also ask

How do you sort an array of objects in Objective C?

NSSortDescriptor *sortDescriptor; sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"birthDate" ascending:YES]; NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor]; NSArray *sortedArray = [drinkDetails sortedArrayUsingDescriptors:sortDescriptors];

How do you sort an array in ascending order in Objective C?

If you wanted to sort your employee's by Manager's lastName, you can do that: NSSortDescriptor *sd1 = [[NSSortDescriptor alloc] initWithKey:@"manager. lastName" ascending:YES]; data = [data sortedArrayUsingDescriptors:@[sd]];

What is swift NSArray?

An object representing a static ordered collection, for use instead of an Array constant in cases that require reference semantics.


1 Answers

That's quite simple to do.

First, in your Foo object, create a method

- (NSComparisonResult) compareWithAnotherFoo:(Foo*) anotherFoo;

Which will return

[[self dateCreated] compare:[anotherFoo dateCreated]];

In the end, call on the array

[yourArray sortUsingSelector:@selector(compareWithAnotherFoo:)];

Hope this helps, Paul

like image 119
Pawel Avatar answered Oct 21 '22 09:10

Pawel