0

価格フィールドに基づいてNSMutableArrayofをソートしようとしています。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*)'
4

1 に答える 1

3

エラーが示すように、priceComparator関数はではなくreturn として宣言する必要がありNSIntegerNSString *ます。

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...返すことにも注意してください。したがって、上記のサンプル コードの宣言です。ソートされた配列を変更可能にする必要がある場合は、NSMutableArrayのorメソッドを使用して配列をその場でソートできます。これらのメソッドは を返すため、結果を変数に割り当てず、オブジェクトをその場で変更することに注意してください。NSArrayNSMutableArraysortedProductssortUsingFunction:context:sortUsingDescriptors:voidarrayProduct

于 2013-08-07T03:39:47.907 に答える