2013-08-07 21 views
0

我想根據價格字段對NSMutableDictionaryNSMutableArray進行排序。嘗試使用sortedArrayUsingFunction排序時出現「不兼容的指針類型..」

NSString* priceComparator(NSMutableDictionary *obj1, NSMutableDictionary *obj2, void *context){ 

    return @"just for test for the moment"; 

} 

//In other function 
arrayProduct = (NSMutableArray*)[arrayProduct sortedArrayUsingFunction:priceComparator context:nil];//arrayProduct is NSMutableArray containing NSDictionarys 

在上面的語句中,我得到以下警告,我想修復:

Incompatible pointer types sending 'NSString*(NSMutableDictionary *__strong,NSMutableDictionary *__strong,void*)' to parameter of type 'NSInteger (*)(__strong id, __strong id, void*)' 

回答

3

由於錯誤狀態,您priceComparator功能needs to be declared as returning NSInteger,不NSString *

NSInteger priceComparator(NSMutableDictionary *obj1, NSMutableDictionary *obj2, void *context){ 
    if (/* obj1 should sort before obj2 */) 
     return NSOrderedAscending; 
    else if (/* obj1 should sort after obj2 */) 
     return NSOrderedDescending; 
    else 
     return NSOrderedSame; 
} 

更好的是,如果您需要排序的價格是一個簡單的數值,那麼您可以使用NSSortDescriptors這些字典中的一個給定的關鍵字。我認爲這是語法:

id descriptor = [NSSortDescriptor sortDescriptorWithKey:@"price" ascending:YES]; 
NSArray *sortedProducts = [arrayProduct sortedArrayUsingDescriptors:@[descriptor]]; 

另外請注意,所有的sortedArray...方法返回一個新的,簡單的NSArray對象,而不是NSMutableArray。因此上面示例代碼中的sortedProducts聲明。如果你真的需要你的排序數組仍然是可變的,你可以使用NSMutableArray的sortUsingFunction:context: or sortUsingDescriptors:方法來就地排序數組。請注意,這些方法返回void,因此您不會將結果分配給任何變量,它會就地修改您的arrayProduct對象。