[英]How to sort using NSSortDescriptor and complex logic?
我有以下代碼按升序排序。
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;
}
}
使用升序對其余部分進行排序(當前的操作方式)
我將如何做呢?
我知道我早些時候問過這個問題,也許我以錯誤的方式提出了問題,但這不是我想要的。 我希望能夠基於函數的結果進行排序。 然后按字母順序。
更新的代碼:
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
}];
這是使用自定義邏輯對數組進行排序的方法,並按字母順序進行平局決勝:
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];
}];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.