0

I have a NSArray of objects. Each object has several properties.

For example: The NSArray oneArray has 5 objects. Each object has the following properties: name, address, ZIP_Code.

How can I sort the NSArray, by name?

1

3 Answers 3

4
NSSortDescriptor* dx = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
NSSortDescriptor* dy = [[NSSortDescriptor alloc] initWithKey:@"address" ascending:NO selector:@selector(caseInsensitiveCompare:)];
[arr sortUsingDescriptors:[NSArray arrayWithObjects:dx, dy, nil]];
[dx release];
[dy release];

Taken from code posted by KennyTM. Edited by Jordan to actually work ;) Replace Array arr with your array. Modify to suit.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 note that this only works if arr is an NSMutableArray. If arr is an NSArray, then you have to use -sortedArrayUsingDescriptors: and capture the return value.
1
    NSInteger nameSort(id obj1, id obj2, void *context)
    {
        NSComparisonResult result = [obj1.name compare:obj2.name];

        if (result == NSOrderedAscending) // stringOne < stringTwo
            return NSOrderedAscending;

        if (result == NSOrderedDescending) // stringOne > stringTwo
            return NSOrderedDecending;

        if (result == NSOrderedSame) // stringOne == stringTwo
            return NSOrderedSame;
    }
/*to sort oneArray*/ oneArray = [oneArray sortedArrayUsingFunction:nameSort context:NULL];

1 Comment

Those ifs are unnecessary, just return result.
1

I like Jordan's answer because (1) I didn't know about NSSortDescriptor and (2) it's useful for sorting on multiple properties.

But what I usually do is create a method like -(NSComparisionResult)compare:(MyClass*)otherObject in my class, then use -[myArray sortedArrayUsingSelector:@selector(compare:)]. The compare method itself is similar to Jumhyn's answer, but I think is a little cleaner because the class itself compares the objects, instead of a stand-alone function.

1 Comment

+1 for your answer! Your idea also great. This is similar to the Comparator in Java!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.