when to use respondsToSelector in objective-c

后端 未结 4 908
挽巷
挽巷 2020-11-29 18:05
- (void)someMethod
{
    if ( [delegate respondsToSelector:@selector(operationShouldProceed)] )
    {
        if ( [delegate operationShouldProceed] )
        {
             


        
4条回答
  •  星月不相逢
    2020-11-29 18:43

    As kubi mentioned respondsToSelector is normally used when you have a an instance of a method that conforms to a protocol.

    // Extend from the NSObject protocol so it is safe to call `respondsToSelector` 
    @protocol MyProtocol  
    
    // @required by default
    - (void) requiredMethod;
    
    @optional
    
    - (void)optionalMethod;
    
    @end
    

    Given and instance of this protocol we can safely call any required method.

    id  myObject = ... 
    [myObject requiredMethod];
    

    However, optional methods may or may not be implemented, so you need to check at runtime.

    if ([myObject respondsToSelector:@selector(optionalMethod)]) 
    {
         [myObject optionalMethod];
    }
    

    Doing this will prevent a crash with an unrecognised selector.


    Also, the reason why you should declare protocols as an extension of NSObjects, i.e.

    @protocol MyProtocol  
    

    Is because the NSObject protocol declares the respondsToSelector: selector. Otherwise XCode would think that it is unsafe to call it.

提交回复
热议问题