How to Sort an NSMutableArray of Managed Objects through an object graph

六眼飞鱼酱① 提交于 2019-11-29 06:11:14

If you can target 10.6, you can accomplish this using blocks. Like so:

- (NSArray *)sortedArray {
    return [originalArray sortedArrayUsingComparator:(NSComparator)^(id obj1, id obj2){
    NSString *lastName1 = [[obj1 person] lastName];
    NSString *lastName2 = [[obj2 person] lastName];
    return [lastName1 caseInsensitiveCompare:lastName2]; }];
}

You can sort like so:

[myUnsortedArrayOfCowboys sortedArrayUsingDescriptors:
    [NSArray arrayWithObject:
        [NSSortDescriptor
            sortDescriptorWithKey:"person.lastName"
            ascending:YES]]];

Notice the '.' in the sort descriptor key. This is how you traverse the object graph.

Abhishek

If you want to sort number and string then use this

NSArray *unsortedArray = [NSArray arrayWithObjects:@"Hello", @"4", @"Hi", @"5", @"2", @"10", @"1", nil];
NSArray *sortedArray = [unsortedArray sortedArrayUsingComparator:^(id firstObject, id secondObject) {
    return [((NSString *)firstObject) compare:((NSString *)secondObject) options:NSNumericSearch];
}];

Hopefully someone has a better solution. However....

A wrapper object with a compare selector and a reference to the sort object works. It is not as clean as I would like so hopefully someone else will come up with an alternative.

In essence CowboyWrapper has a cowboy property. CowboyWrapper also has a compare selector. By building and keeping in sync an NSMutableArray of CowboyWrappers, sort works.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!