我有一個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;
}
感謝DHamrick。這是完美的。我想我現在明白了好一點... – Simple99 2012-01-28 16:18:18