开发者

Sort NSMutableArray with objects with uniqueID

I've looked around the web and know that one of the ways to sort an NSMutableArray is by using sortUsingSelector:. But I'm still a little shaky on exactly what needs to be done. I know that the comparator method should return NSOrderedAscending or NSOrderedDescending in order to do the sorting, but I need a little more help.

开发者_如何学JAVA

I have an array of Block objects. Each Block has a unique ID ranging from 1 to 200+. I'd like to sort the array based on the Block objects uniqueID. Is this possible?

NSMutableArray *array = [[NSMutableArray alloc] init];
for (unsigned i = 0; i < 221; i++) {
    Block *block = [[Block alloc] init];
    block.uniqueId = i;
    [array addObject:block];
    [block release];
}

Now, obviously this array is sorted after initialization, but I add and remove Blocks later, and would like to resort the array afterwards. Please help!


Another option is using sort descriptors. They are based on properties within the object. You can do it in one line like this:

NSArray* sorted =[array sortedArrayUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"uniqueId" ascending:YES]]];

or create them separately

NSSortDescriptor* idDescriptor=[NSSortDescriptor sortDescriptorWithKey:@"uniqueID" ascending:YES]
NSArray* descriptors=[NSArray arrayWithObject: idDescriptor];
NSArray* sortedArray=[array sortedArrayUsingDescriptors: descriptors];

With this option you can specify multiple levels of sorting by adding multiple NSSortDescriptors to the descriptors array.


NSArray *sortedArray = [array sortedArrayUsingComparator:^(id o1, id o2) {
    int id1 = ((Block *)o1).uniqueId;
    int id2 = ((Block *)o2).uniqueId;

    if (id1 == id2) {
        return NSOrderedSame;
    }
    if (id1 < id2) {
        return NSOrderedAscending;
    }
    return NSOrderedDescending;
}];
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜