开发者

How to sort an NSArray with objects

开发者 https://www.devze.com 2023-01-30 16:37 出处:网络
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.

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?


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.


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消