2011-12-12 36 views
0

我有以下代碼按升序排序。如何使用NSSortDescriptor和複雜的邏輯進行排序?

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

我想要做的是做一個排序,其中:

顯示在正在其次是積極的當前用戶(複雜的邏輯中去的功能?)

一個sortedRelease的那些這是我需要在我的自定義功能:使用acsending

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

回答

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]; 
}]; 
+0

上都能夠的iOS 4和iOS 5設備這項工作? – jini

+0

是的,它可以與iOS 4.0或更新版本兼容。這意味着除第一代iPhone和iPod Touch之外的所有硬件都受支持,除非用戶特意選擇不安裝免費升級(例如:因爲他們的手機已越獄)。向後兼容的替代方法是'sortedArrayUsingSelector:',但鼓勵您使用由@dasblinkenlight發佈的新塊API –

+0

是的:根據Apple文檔,此功能在iOS 4.0及更高版本中爲可用。 – dasblinkenlight