Possible to tell if a subclass overrode a method?
While working on a small project I found myself needing to do some custom drawing via drawRect:
in one of my UIView
subclasses. I noticed when I overrode drawRect:
that the default background color of the UIView
subclass had changed from transparent to black (by default background color I mean the color the v开发者_JAVA百科iew draws itself when its backgroundColor
property is nil.) Even with an empty drawRect:
or a drawRect:
that simply calls [super drawRect:]
I noticed this behavior.
This isn't really a problem, as simply setting a backgroundColor
to a non-nil value works regardless of whether drawRect:
is overridden. However, it did make me start thinking about how UIView
knows whether drawRect:
is overridden by a subclass. I know Objective-C offers facilities to determine if a class or even its superclass responds to a certain selector. But how could a superclass possibly know if its subclass has overridden one of its methods? And, if this type of introspection is indeed impossible, what could be going on in my example?
That is pretty bizarre (but sounds like it is intended). Simply adding:
- (void) drawRect:...
{
[super drawRect:...];
}
Triggers the behavior? Atypical. In any case, it is trivial to use the Objective-C runtime API to introspect class implementation details quite thoroughly. See the Objective-C runtime reference.
UIView's documentation for -drawRect:
goes into considerable detail about subclassing. It quite specifically states that you don't need to call super when directly subclassing UIView
, indicating that the class is likely optimized to doing the minimal amount of extra work (like drawing a background that is obliterated entirely in your implementation).
精彩评论