2012-11-02 32 views
16
-(NSMutableArray *)sortArrayByProminent:(NSArray *)arrayObject 
{ 
    NSArray * array = [arrayObject sortedArrayUsingComparator:^(id obj1, id obj2) { 
     Business * objj1=obj1; 
     Business * objj2=obj2; 
     NSUInteger prom1=[objj1 .prominent intValue]; 
     NSUInteger prom2=[objj2 .prominent intValue]; 
     if (prom1 > prom2) { 
      return NSOrderedAscending; 
     } 
     if (prom1 < prom2) { 
      return NSOrderedDescending; 
     } 
     return NSOrderedSame; 
    }]; 

    NSMutableArray *arrayHasBeenSorted = [NSMutableArray arrayWithArray:array]; 

    return arrayHasBeenSorted; 
} 

所以基本上我有這個塊,我用來排序數組。如何創建一個返回塊的objective-c方法

現在我想寫一個返回該塊的方法。

我該怎麼做?

我試圖

+ (NSComparator)(^)(id obj1, id obj2) 
{ 
    (NSComparator)(^ block)(id obj1, id obj2) = {...} 
    return block; 
} 

這麼說吧,它尚不能工作。

+0

究竟什麼叫「它不工作」是什麼意思?對於正確的錯誤描述,這太寬泛了。 – 2012-11-02 10:45:28

回答

50

方法簽名返回這樣的塊應該是

+(NSInteger (^)(id, id))comparitorBlock { 
    .... 
} 

這種分解:

+(NSInteger (^)(id, id))comparitorBlock; 
^^ ^ ^^ ^^  ^
ab c  d e e b  f 

a = Static Method 
b = Return type parenthesis for the method[just like +(void)...] 
c = Return type of the block 
d = Indicates this is a block (no need for block names, it's just a type, not an instance) 
e = Set of parameters, again no names needed 
f = Name of method to call to obtain said block 

更新:在你的特殊情況,NSComparator已經是塊型的。它的定義是:

typedef NSComparisonResult (^NSComparator)(id obj1, id obj2); 

因此,所有你需要做的就是返回此類型定義:

+ (NSComparator)comparator { 
    .... 
} 
+3

沒有。 'NSComparator'已經是一個塊類型。您可能是指'+(NSComparisonResult(^)(id,id))比較器或'+(NSComparator)比較器'。 – 2012-11-02 11:04:01

+0

糟糕,疏忽!謝謝。是的,至少對於這個問題,我會使用兩個中的「+(NSComparator)比較器」。 – WDUK

+0

你會先更新答案嗎? –

相關問題