2012-11-02 18 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; 
} 

Quindi in pratica ho questo blocco che uso per ordinare la matrice.Come creare un metodo obiettivo-c che restituisce un blocco

Ora voglio scrivere un metodo che restituisca quel blocco.

Come faccio?

ho cercato

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

diciamo solo che non funziona ancora.

+0

Esattamente che cosa si intende per "non funziona"? È troppo generico per una corretta descrizione dell'errore. –

risposta

50

Una firma metodo per restituire un blocco come questo dovrebbe essere

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

Questo si decompone a:

+(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 

Update: In vostra situazione particolare, NSComparator è già di un tipo di blocco. La sua definizione è:

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

Come tale, tutto quello che dovete fare è restituire questa typedef:

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

No. 'NSComparator' è già un tipo di blocco. Probabilmente si intendeva o un comparatore '+ (NSComparisonResult (^) (id, id)) o' + (NSComparator)'. –

+0

Oops, supervisione! Grazie. Sì, andrei con '+ (NSComparator) comparatore dei due, almeno per questa domanda. – WDUK

+0

Vuoi aggiornare prima la risposta? –

Problemi correlati