How to get rid of the 'undeclared selector' warning

前端 未结 12 2119
伪装坚强ぢ
伪装坚强ぢ 2020-12-12 10:53

I want to use a selector on an NSObject instance without the need for an implemented protocol. For example, there\'s a category method that should set an error prop

相关标签:
12条回答
  • 2020-12-12 11:19

    I was able to get the warning to go away by adding thenothing method (disclosure: I didn't think of this but found it by googling on scheduledtimerwithtimeinterval)

        [NSTimer scheduledTimerWithTimeInterval:[[NSDate distantFuture] timeIntervalSinceNow]
                                         target:self
                                       selector:@selector(donothingatall:)
                                       userInfo:nil
                                        repeats:YES];
    
    
        [[NSRunLoop currentRunLoop] run];
    
        HTTPLogVerbose(@"%@: BonjourThread: Aborted", THIS_FILE);
    
        }
    }
    
    + (void) donothingatall:(NSTimer *)timer
    {
    
    }
    

    While I appreciate knowing how to hide the warning, fixing it is better and neither Sergio's nor Relkin's techniques worked for me, for unknown reasons.

    0 讨论(0)
  • 2020-12-12 11:21

    You can turn it off in Xcode like in the screenshot:

    0 讨论(0)
  • 2020-12-12 11:25

    You can also cast the object in question to an id first to avoid the warning:

    if ([object respondsToSelector:@selector(myMethod)]) {
        [(id)object myMethod];
    }
    
    0 讨论(0)
  • 2020-12-12 11:26

    Another way to avoid this warning is to make sure your selector method looks like this:

    -(void) myMethod :(id) sender{
    }
    

    Don't forget "(id) sender" if you want to accept any sender or specify a type of a sender object if you prefer.

    0 讨论(0)
  • Have a look at NSSelectorFromString.

     SEL selector = NSSelectorFromString(@"setError:");
     if ([self respondsToSelector:selector])
    

    It will allow you to create a selector at runtime, instead of at compile time through the @selector keyword, and the compiler will have no chance to complain.

    0 讨论(0)
  • 2020-12-12 11:30

    If your class implements the setError: method (even by declaring dynamic the setter of the eventual error property) you might want to declare it in your interface file ( .h), or if you don't like to show it that way you could try with the PrivateMethods tricky trick:

    @interface Yourclass (PrivateMethods)
    
    - (void) yourMethod1;
    - (void) yourMethod2;
    
    @end
    

    just before your @implementation , this should hide the warnings ;).

    0 讨论(0)
提交回复
热议问题