简体   繁体   中英

selector syntax: why I am getting unrecognized selector error?

I have a method to compare 2 objects:

- (NSComparisonResult)compare:(NSObject *)object1 to:(NSObject *)object2{
    // do some stuff
    return NSOrderedSame; // or NSOrderedAscending or NSOrderedDescending
}

This method gets called like this:

NSArray *sortedSyncedAufgaben = [syncedAufgabe sortedArrayUsingSelector:@selector(compare:to:)];

Now, when I run this on my iPhone, a "unrecognized selector error" is thrown in the line with the selector:

* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[ImpfVorgang compare:to:]: unrecognized selector sent to instance 0x14ebf040'

What is wrong? I thought for each parameter I need a colon?

sortedArrayUsingSelector: tries to apply you selector to the object on the left-hand side of the comparison, not to the class that calls sortedArrayUsingSelector: . In other words, if the selector exists in your class that initiates the sort, not in the class of the object inside NSArray (ie not in your ImpfVorgang class), you are going to see an "unrecognized selector error".

You can change your code to apply the selector manually, like this:

NSArray * sortedSyncedAufgaben = [syncedAufgabe sortedArrayUsingComparator:^(NSObject *a, NSObject* b) {
    return [self compare:a to:b];
}];

Alternatively, you could move the comparison logic into the comparator block, and drop the compare:to: method altogether.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM