如何使用NSSortDescriptor和复杂逻辑进行排序?

时间:2011-12-12 01:48:04

标签: iphone objective-c ios nssortdescriptor

我有以下代码按升序排序。

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"someproperty.name" ascending:YES];
    NSMutableArray   *sortedReleases = [NSMutableArray arrayWithArray:[unsortedarray sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]]];
    [sortDescriptor release];

我想做的是做一个分类:

显示当前有效用户所遵循sortedRelease的那些(函数中的复杂逻辑?)

这是我在自定义函数中需要的:

for (Release *release in sortedReleases){

if( [[[MainController sharedMainController] activeUser] isFollowingRelease:release] ){

return NSOrderedAscending;
}

}

使用acsending(当前如何进行)对其余部分进行排序

我将如何做到这一点?

我知道我之前问了这个问题,也许我问的方法不对,但那不是我想要的。我希望能够根据函数的结果进行排序。然后按字母顺序排列。

更新代码:

 NSArray *sortedReleases = [theReleases sortedArrayUsingComparator:^(id a, id b) {
        Release *left = (Release*)a;
        Release *right = (Release*)b;


        if(( [[[MainController sharedMainController] activeUser] isFollowingRelease:left] )&&([[[MainController sharedMainController] activeUser] isFollowingRelease:right])){

           //sort alphabetically ????
        }
        else if (([[[MainController sharedMainController] activeUser] isFollowingRelease:left])&&(![[[MainController sharedMainController] activeUser] isFollowingRelease:right]))
        {
            return (NSComparisonResult)NSOrderedDescending;
        }
        else if ((![[[MainController sharedMainController] activeUser] isFollowingRelease:left])&&([[[MainController sharedMainController] activeUser] isFollowingRelease:right]))
        {
             return (NSComparisonResult)NSOrderedAscending;
        }

        return [left compare:right]; //getting a warning here about incompatible types
    }];

1 个答案:

答案 0 :(得分:3)

以下是使用自定义逻辑对数组进行排序的方法,以及用于打破平局的字母排序:

NSArray *sortedArray = [unsortedArray sortedArrayUsingComparator:^(id a, id b) {
    Release *left = (Release*)a;
    Release *right = (Release*)b;
    BOOL isFollowingLeft = [[[MainController sharedMainController] activeUser] isFollowingRelease:left];
    BOOL isFollowingRight = [[[MainController sharedMainController] activeUser] isFollowingRelease:right];
    if (isFollowingLeft && !isFollowingRight) {
        return (NSComparisonResult)NSOrderedDescending;
    } else if (!isFollowingLeft && isFollowingRight) {
        return (NSComparisonResult)NSOrderedDescending;
    }
    return [left.name compare:right.name];
}];