Reputation: 16286
I am trying to sort an NSMutableArray
of NSMutableDictionary
s basing on a price field.
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
On the statement above, I am getting the following warning which I want to fix:
Incompatible pointer types sending 'NSString*(NSMutableDictionary *__strong,NSMutableDictionary *__strong,void*)' to parameter of type 'NSInteger (*)(__strong id, __strong id, void*)'
Upvotes: 1
Views: 268
Reputation: 12025
As the error states, your priceComparator
function needs to be declared as returning NSInteger
, not 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;
}
Better yet, you could use NSSortDescriptors
if the price you need to sort by is a simple numeric value that's always at a given key in these dictionaries. I think this is the syntax:
id descriptor = [NSSortDescriptor sortDescriptorWithKey:@"price" ascending:YES];
NSArray *sortedProducts = [arrayProduct sortedArrayUsingDescriptors:@[descriptor]];
Also note that all of the sortedArray...
methods return a new, plain NSArray
object, not a NSMutableArray
. Thus the sortedProducts
declaration in the sample code above. If you really do need your sorted array to still be mutable, you could use the sortUsingFunction:context:
or sortUsingDescriptors:
method of NSMutableArray to sort the array in-place. Note that these methods return void
, so you wouldn't assign the result to any variable, it would modify your arrayProduct
object in-place.
Upvotes: 4