super respondsToSelector: returns true but actually calling super (selector) gives “unrecognized selector sent to instance”

后端 未结 5 1712
不知归路
不知归路 2021-01-01 12:40

OK, I am a little confused.

I have a subclass of UIScrollView, which is my attempt at a horizontally scrolling \"table view\" like UI element. UIScrollView itself s

5条回答
  •  我在风中等你
    2021-01-01 13:42

    After looking at the other answers, the best solution is to use [[MapControllerSublcass1 superclass] instancesRespondToSelector:_cmd]. If you use what is recommended above, something like [BaseClass instancesRespondToSelector:_cmd], you run into the problem of changing your class hierarchy and accidentally forgetting to change BaseClass to the new superclass or your subclass.

    [[self superclass] instancesRespondToSelector:...] is incorrect as explained above in the comments and it actually says so on Apple's documentation (See respondsToSelector: in NSObjct). It only works when you have 1 level of subclassing, so it gives you the illusion that it is an actual solution. I fell for it.

    And [[super class] instancesRespondToSelector:...] doesn't work and is the whole point of this SO question.

    For example, I have a BaseMapController that implements some of the methods in MKMapViewDelegate, but it doesn't implement mapView:regionWillChangeAnimated:. MapControllerSublcass1 inherits from BaseMapController. And MapControllerSubclass2 inherits from MapControllerSublcass1.

    In my code I have something like this, and it works fine.

    MapControllerSublcass1.m:

    - (void)mapView:(MKMapView *)mapView regionWillChangeAnimated:(BOOL)animated {
      if ([[MapControllerSublcass1 superclass] instancesRespondToSelector:_cmd]) {
        [super mapView:mapView regionWillChangeAnimated:animated];
      }
    }
    

    MapControllerSubclass2.m:

    - (void)mapView:(MKMapView *)mapView regionWillChangeAnimated:(BOOL)animated {
      if ([[MapControllerSubclass2 superclass] instancesRespondToSelector:_cmd]) {
        [super mapView:mapView regionWillChangeAnimated:animated];
      }
    }
    

提交回复
热议问题