Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

when to use respondsToSelector in objective-c

- (void)someMethod {     if ( [delegate respondsToSelector:@selector(operationShouldProceed)] )     {         if ( [delegate operationShouldProceed] )         {             // do something appropriate         }     } } 

The documentation says:

The precaution is necessary only for optional methods in a formal protocol or methods of an informal protocol

What does it mean? If I use a formal protocol I can just use [delegate myMethod]?

like image 762
Taho Avatar asked Sep 12 '10 23:09

Taho


People also ask

What is Respondstoselector in Objective-C?

Returns a Boolean value that indicates whether the receiver implements or inherits a method that can respond to a specified message.

What is Nsobject in Swift?

The root class of most Objective-C class hierarchies, from which subclasses inherit a basic interface to the runtime system and the ability to behave as Objective-C objects.


2 Answers

You use it pretty much just when you think you need to: to check to see if an object implements the method you are about to call. Usually this is done when you have an optional methods or an informal protocol.

I've only ever used respondsToSelector when I'm writing code that must communicate with a delegate object.

if ([self.delegate respondsToSelector:@selector(engineDidStartRunning:)]) {         [self.delegate engineDidStartRunning:self];     } 

You sometimes would want to use respondsToSelector on any method that returns and id or generic NSObject where you aren't sure what the class of the returned object is.

like image 84
kubi Avatar answered Oct 22 '22 02:10

kubi


Just to add to what @kubi said, another time I use it is when a method was added to a pre-existing class in a newer version of the frameworks, but I still need to be backwards-compatible. For example:

if ([myObject respondsToSelector:@selector(doAwesomeNewThing)]) {   [myObject doAwesomeNewThing]; } else {   [self doOldWorkaroundHackWithObject:myObject]; } 
like image 21
Dave DeLong Avatar answered Oct 22 '22 03:10

Dave DeLong