2012-01-28 22 views
3

我有一個switch語句,它創建相關的NSSortDescriptor。對於NSSortDescriptors中的一些,我使用block作爲自定義comparator(以比較CMTimes)。下面的代碼工作正常,但我想添加更多NSSortDescriptors也比較CMTimes。由於block始終是相同的,因此可以創建variable來保存block,因此我不需要繼續複製和粘貼混亂的代碼。我想這應該是可能的,但我似乎無法得到它的工作。我將不勝感激任何幫助。謝謝!NSSortDescriptors中的塊 - 目標C

NSSortDescriptor *sortDescriptor; 

switch (mode) { 
    case 1: 
     sortDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"startTime" ascending: YES comparator:^(id first, id second){ 
        CMTime time1 = [first CMTimeValue]; 
        CMTime time2 = [second CMTimeValue]; 
        if (CMTIME_COMPARE_INLINE(time1, <, time2)) 
         return NSOrderedAscending; 
        else if (CMTIME_COMPARE_INLINE(time1, >, time2)) 
         return NSOrderedDescending; 
        else 
         return NSOrderedSame; 
     }]; 
     break; 
    case 2: 
     sortDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"startTime" ascending: NO comparator:^(id first, id second){ 
        CMTime time1 = [first CMTimeValue]; 
        CMTime time2 = [second CMTimeValue]; 
        if (CMTIME_COMPARE_INLINE(time1, <, time2)) 
         return NSOrderedAscending; 
        else if (CMTIME_COMPARE_INLINE(time1, >, time2)) 
         return NSOrderedDescending; 
        else 
         return NSOrderedSame; 
     }]; 
     break; 
    case 3: 
     sortDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"info" ascending: YES]; 
     break; 
    case 4:  
     sortDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"info" ascending: NO]; 
     break; 
    default: 
     break; 
} 

回答

9

您可以創建塊變量,以便不必複製和粘貼塊代碼。

NSComparator comparisonBlock = ^(id first,id second) { 
    return NSOrderedAscending; 
}; 
[NSSortDescriptor sortDescriptorWithKey: @"startTime" ascending: YES comparator:comparisonBlock]; 
+0

感謝DHamrick。這是完美的。我想我現在明白了好一點... – Simple99 2012-01-28 16:18:18

1

當然,使用@property (nonatomic, copy)作爲屬性(不要忘記釋放),或者只是在分配之前定義一個塊。

4

你可以做沿

NSComparator myBlock = ^(id first, id second) { 
    CMTime time1 = [first CMTimeValue]; 
    CMTime time2 = [second CMTimeValue]; 
    if (CMTIME_COMPARE_INLINE(time1, <, time2)) 
     return NSOrderedAscending; 
    else if (CMTIME_COMPARE_INLINE(time1, >, time2)) 
     return NSOrderedDescending; 
    else 
     return NSOrderedSame; 
} 

這將創建你的變量myBlock是與返回類型NSComparator塊線的東西,並採取兩種標識類型參數。

然後,您應該能夠調用例如:

sortDescriptor = [NSSortDescriptor sortDescriptorWithKey: @"startTime" ascending: YES comparator:myBlock]; 

,一切都應該很好地工作。

希望這可以幫助,讓我知道如果有什麼我可以幫助:)

+0

Hi George。出於某種原因,我無法讓你的解決方案工作......特別是......(^ myBlock)(id,id)'。如果我只是用'myBlock'替換它,就像在上面的DHamrick的答案中一樣,它工作正常。 – Simple99 2012-01-28 16:32:32

+0

對不起,那完全是我的錯。你說得對,我輸錯了。 – 2012-01-28 17:18:32