“不兼容的指针类型..”尝试使用`sortedArrayUsingFunction`进行排序时

时间:2013-08-07 03:36:12

标签: ios nsmutablearray

我正在尝试根据价格字段对NSMutableArray NSMutableDictionary进行排序。

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*)'

1 个答案:

答案 0 :(得分: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对象。

相关问题