Most overlo开发者_开发技巧aded methods require [super theMethod]
call.
(For example, [super viewDidLoad];
, [super viewWillAppear];
and [super dealloc];
)
I didn't think twice whether I need [super touchesBegan:withEvent:]
call or not, but it seems to play a role somehow.
When do I need it and when don't I need it?
I'm trying to programmatically cancel touch events when I need to, and it seems to be related to the question I asked.
While it all depends on the expected behaviors of the object, let's point out the basic: You call the superclass implementation in an overridden method (you mean overriding, not overloading) if you want default behaviors implemented by the superclass.
So the questions you should ask are:
1) What does the superclass implementation do?
2) Do I need it for my object?
So what does touchesBegan:withEvent:
etc. of your superclass do? It depends on your class hierarchy. The custom classes in your class hierarchy may already override those methods and you may want those behaviors, or not. I assume that no custom class has yet overridden those methods, so you have to check Cocoa implementations only.
touchesBegan:withEvent:
is first defined in UIResponder class. Let's look at the UIResponder documentation, which says
The default implementation of this method does nothing. However immediate UIKit subclasses of UIResponder, particularly UIView, forward the message up the responder chain.
So you get a theory here. If your class directly inherits from UIResponder, you don't need to call the superclass implementation at all as it does nothing anyway. If it inherits from other UIKit subclasses such as UIView, calling the superclass implementation will enable forwarding messages up the responder chain. However, overriding touchesBegan:withEvent:
perhaps means that your subclass wants to handle touch events itself, so you don't want to forward the events up the responder chain. So, I guess you don't want to call the superclass implementation here.
It really depends on the situation. Say, that you subclass a UIScrollView, and implements one of the touches...
method. If you still want the view to scroll as the user drags, then you want to call the superclass implementation because it will handle scrolling for you.
To sum up, you have to be able to answer the two questions above to decide. To find out what a superclass implementation does, read about it in the Apple Documentation. In many cases, if what a superclass implementation does is essential for common expected behaviors, the guide documents give an explicit advice to call the superclass implementation.
精彩评论