when to use respondsToSelector in objective-c

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


        
4条回答
  •  一个人的身影
    2020-11-29 18:59

    Old question, but I have learned to be very cautios with using stuff like addTarget:@selector(fu:) because the method name is not checked nor included in refactoring by XCODE. This has caused me quite some trouble already. So now I made it a habbit to always embed stuff like addTarget or addObserver in a respondsToSelector-Check like so:

    if([self respondsToSelector:@selector(buttonClicked:)]){
        [self.button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
    }else{
        DebugLog(@"Warning - a class or delegate did not respond to selector in class %@", self);
    } 
    

    I know its not super elegant, but i'd rather add some boilerplate code than have an unexpected crash of my apps in the App Store.

提交回复
热议问题