(iphone) what does [super touchesBegan/Moved/Ended] do? - iphone

Most overloaded 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.

Related

Why not subclass UIApplication? Why use a delegate?

Instead of using an application delegate so that the UIApplication singleton can call the delegate methods at predefined time, what are the advantages and disadvantages of just subclassing UIApplication? (update: why does the iOS architecture use the application delegate instead of letting people write an application by subclassing UIApplication and overriding its various methods?)
That's because when we create a new UIView control, we subclass UIView (update: or we subclass UIViewController too). So why for the case of application, we don't subclass UIApplication but use delegation instead?
Again, from the documentation:
Subclassing Notes
You might decide to subclass UIApplication to override sendEvent: or
sendAction:to:from:forEvent: to implement custom event and action
dispatching. However, there is rarely a valid need to extend this
class; the application delegate (UIApplicationDelegate is sufficient
for most occasions. If you do subclass UIApplication, be very sure of
what you are trying to accomplish with the subclass.
From the UIApplication Class Reference:
The UIApplication class provides a centralized point of control and coordination for applications running on iOS.
Every application must have exactly one instance of UIApplication (or a subclass of UIApplication). When an application is launched, the UIApplicationMain function is called; among its other tasks, this function creates a singleton UIApplication object. Thereafter you can access this object by invoking the sharedApplication class method.
So what do you mean by "why don't we subclass UIApplication? Apple even provides notes on what to implement in subclasses.
As for your question about delegation and singleton use over just standard classes, the answer is simple: An application must provide one common way to recieve and dispatch events (both external and system related), handle multitasking, and interface loosely with the system (that's why main.m includes a reference to your app delegate).
The reason developers usually don't is because there is no need to. UIApplication works as it needs to for the majority of cases. It just needs some hints on what to do in certain predefined cases (which is why it has a delegate). UIView, on the other hand, is very generic and I don't think it is ever used as-is. It is probably the most customized class in all of the iOS world.
Delegation is a core design pattern. It allows for the seperation of responsibilities between parts of your program. The idea is that the part of your program that, for example, draws to the screen probably shouldn't be talking to your database. There are several reasons for this:
Performance: if the same object that draws to the screen access your data store, you're going to run into performance problems. Period. Full stop.
Code maintanence: it's easier to conceptualize code that is properly modularized. (For me, anyway)
Flexibility: If you subclass in your code, that's great - until you start running into monolithic classes that have all sorts of undesired behavior. You'll reach the point where you have to overload behaviors to turn things off, and your property namespace can become polluted. Try categories, delegatation, and blocks for alternatives.
That said, I did indeed run into a situation where subclassing was appropriate. I have a kiosk app in which I wanted to automatically dismiss a certain settings menu if it wasn't interacted with for a period of time. To do so, I had to have access to touch events throughout the entire app. I subclassed UIApplication and overrode sendEvent:. That was appropriate then, although it's an edge case. As king Solomon says in Ecclesiastes, paraphrased: There's a time and place for everything under the sun.
To make it easier to write, read, iterate upon, and maintain your program, it is strongly advised that you follow certain practices. You're welcome to subclass many classes, and Apple won't reject your app for poor code, provided that it runs as advertised. That said, if you don't abide by specific tried and true practices, you're digging your own grave. Subclassing isn't inherently bad, but categories, protocols, and blocks are so fascinating, that I'd prefer them anyway.
There are many specialized things that a UIView subclass might need to do. Think of UIScrollView, UIImageView, UIWebView, etc., and how drastically different their internal workings must be. But still, they must participate in the view hierarchy and so subclassing makes sense.
UIApplication, on the other hand, is a central hub for application-wide events, notifications, opening URLs, accessing windows, and other generic things. Under normal circumstances, an app should really just need to know things that UIApplicationDelegate Protocol will provide.
A note from the UIApplication Overview explains one reason that you might subclass UIApplication:
You might decide to subclass UIApplication to override sendEvent: or sendAction:to:from:forEvent: to implement custom event and action dispatching. However, there is rarely a valid need to extend this class; the application delegate (UIApplicationDelegate is sufficient for most occasions. If you do subclass UIApplication, be very sure of what you are trying to accomplish with the subclass.
But this should only be necessary in very special cases.
I'll add something no one else mentioned: Delegation removes the need to call super when overriding/augmenting/adding behavior via a delegate method implementation rather than a subclass with an overridden method. I've seen many developers answer their own Stackoverflow question with simply they forgot to call super (after some have even posted possible answers). The newer method decorator NS_REQUIRES_SUPER helps a bit with this by alerting the developer with a warning (hopefully they don't ignore it!) however it doesn't help when the order of the call to super matters. I think Apple decided it was less error-prone to have developers implement a delegate object instead, that has no calling super requirements, and they even did the hard work of forwarding the UIResponder methods from UIApplication on to the delegate object too.

Delegation over category

Can any one differentiate when do we use Delegation over category and vice versa. I am clear over this.
Thanks
Category allows to add new methods or overwrite existing methods on a class, thus allows to extend a class without subclassing. Adding methods is the most useful aim, overwriting can go really wrong if you do not know exactly what the class being extended does.
It is more a language feature not a pattern, it works on each class.
Delegate is a pattern not a language feature, the class that is supposed to used must be coded for it, otherwise it won't work.
Usually a delegate will be required to implement a protocol known by the class that is going to receive the delegate. The class will then use the delegate to do stuff it was coded for, some of the most common are sending notifications, using a part of a strategy pattern, that is asking question in certain part of code to make decisions based on the concrete delegate's implementation, letting delegate execute an action or any combination of them.
For example UIApplicationDelegate is a notification (application:didFinishLaunchingWithOptions:) and action (application:openURL:sourceApplication:annotation:) protocol, UITextFieldDelegate is notification (textFieldDidBeginEditing:) and strategy (textField:shouldChangeCharactersInRange:replacementString:).
Actually I can imagine using category to implement delegating in all this cases I stated above: sending notifications, doing actions, taking part in a strategy. But it would require you to very very good know what to extended class is doing, probably to have it code, otherwise you can very easily break the class or be broken by changed class implementation. So this usage would be in my opinion highly wrong.
category: Adds methods to an existing class.
delegate: Modifies behavior of another object by allowing some other object, the delegate, to participate in the object's operation.
Say you've got an iOS application with three tables. Even though they're configured the same way, those tables each may behave differently if they have different delegates.
You can't do that with a category because a category applies equally to all instances of the class it extends. On the other hand, if you want to extend the UITableView class to add some new capability, you need a category*. Delegates are instance-specific and limited to the role envisioned for them by the designer of the delegating class.
*or a subclass, of course.
Categories are used when you need to extend the class without creating a subclass, for example when you need to add a method named isURL to the NSString you can make use of categories as follows, here we not creating a subclass, instead we are extending the implementation.
#interface NSString (Utilities)
- (BOOL) isURL;
#end
Delegates are similar to callback functions,

Why does Apple's doc say that you don't call the superclass's event handling methods in subclass of UIView?

In Apple's document, Event Handling Guide for iOS, the section "Best Practices for Handling Multitouch Events":
If you handle events in a subclass of UIView, UIViewController, or (in rare cases) UIResponder,
You should implement all of the event-handling methods (even if it is a null implementation).
Do not call the superclass implementation of the methods.
and
If you handle events in a subclass of any other UIKit responder class,
You do not have to implement all of the event-handling methods.
But in the methods you do implement, be sure to call the superclass implementation.
Why? I don't understand the rationale behind point 2 of both cases. Doesn't it depend on the different situations?
It probably relates to the later point:
Do not explicitly send events up the responder (via nextResponder); instead, invoke the superclass implementation and let the UIKit handle responder-chain traversal.
If you handle touchesBegan:withEvent: and touchesEnded:withEvent:, what does UIView do with touchesMoved:withEvent:? Is it supposed to forward it up the responder chain?

Object and view setup and initialization in objective-C

When creating a UIViewController derived class in objective-C, what goes into the init method, what should go into loadView and what into viewDidLoad - and more importantly why, and what benefit (performance?) does this have?
Also, how does this relate to UIView derived classes where the only option you have is the init method?
I know the template code already has comments for what goes into each method, but it unclear to me why each thing goes where they say.
Clarification
I would like to know maybe at a lower level, what is the actual difference between things being done in the 'init', 'loadView' and 'viewDidLoad'. What does the framework do in between these calls that may affect the way/time I set up my views and do other work? How are these methods affected by threading?
You want to know some lower-level stuff.
init: This method gets called on ANY NSObject subclass. It is what sets up the object, which you probably already know. In many model (as in the MVC pattern) classes, init is directly used. As for the UIKit classes, very few requires init to be called directly. It should not be used. In the UIViewController, you initialize it using initWithNibNamed:. You can override this method, but in most cases this is not needed. This method is the VERY first method to EVER get called on the class (before any view setup, or such).
loadView:and viewDidLoad: read this article iPhone SDK: what is the difference between loadView and viewDidLoad? .
The only really important thing to know is that -init is the NSObject standard initialization method. -loadView and -viewDidLoad are UIViewController's methods for initialization.

What are AppDelegates in Objective-C?

I'm working through an iPhone tutorial (link text and it has me put in some code (a few times throughout the various tutorials) but it doesn't explain it at all.
In this code:
todoAppDelegate *appDelegate = (todoAppDelegate *)[[UIApplication sharedApplication] delegate];
What exactly is an appDelegate? What does the "delegate" at the end of the instantiation mean? Actually, what does the whole thing mean? (UIIapplication sharedApplication)?
I am a .Net programmer if that helps someone explain it better. I hate learning through tutorials because I always need to know what EVERYTHING does and no one explains everything.
Let's back up a little bit.
The square brackets ([ ]) are Objective-C's method calling syntax. So if Cocoa had a C# syntax, the equivalent syntax would be:
TodoAppDelegate appDelegate = UIApplication.sharedApplication.delegate;
In C#, you would use a static class for a class that only has a single instance. In Cocoa, the Singleton pattern is used to accomplish this. A class method (in this case, sharedApplication) is used to retrieve the single instance of that class.
Delegates in Cocoa are not like the delegate keyword in C#, so don't be confused by that. In C#, you use the delegate keyword to reference a method. The delegate pattern in Cocoa is provided as an alternative to subclassing.
Many objects allow you to specify another object as a delegate. Delegates implement methods that those objects will call to notify them of certain events. In this case, UIApplication is the class that represents the current running application (similar to System.Windows.Forms.Application, for example). It sends messages to its delegate when things that affect the application happen (e.g. when the application launches, quits, gains or loses focus, and so on.)
Another Objective-C concept is the protocol. It is similar in principle to a .NET interface, except that methods can be marked as #optional, meaning they classes are not required to implement the methods marked that way. Delegates in the iPhone SDK are simply objects that conform to a specific protocol. In the case of UIApplication, the protocol delegates must conform to is UIApplicationDelegate.
Because it's not required to implement every method, this gives the delegate flexibility to decide which methods are worth implementing. If you wanted to, for example, perform some actions when the application finishes launching, you can implement a class that conforms to the UIApplicationDelegate protocol, set it as the UIApplication instance's delegate, and then implement applicationDidFinishLaunching:.
UIApplication will determine if its delegate implements this method when the application finishes launching and, if it does, call that method. This gives you a chance to respond to this event without having to subclass UIApplication.
In iPhone applications, developers also frequently use the app delegate as a kind of top-level object. Since you don't usually subclass UIApplication, most developers keep their global application data in the app delegate.
A delegate is just an object that implements certain methods (basically callbacks). The NSApplication docs explain what its delegate is supposed to do and what messages it needs to respond to to.
And this isn't instantiation. The snippet you posted above doesn't create anything. It accesses whatever object is set as the application's delegate. [UIApplication sharedApplication] gets the object representing the application, and sending delegate to the application gets its delegate (if any).
to add more to the mix of responses and another point of view, delegates are objects that can (but don't necessarily need to) do work for another object.
So let's say you have objectA, and can assign to it a delegate (let's call it delegateObject).
From objectA's point of view, there are certain bits of work that may need to be done. Depending on the context, the actual work and the results of such work can be different.
So instead of having objectA implementing a method for all these instances, we'll say... let's have another object, delegateObject, do the work... and as long as the results are returned in the proper format, we don't care what delegateObject did to get there.
objectA will first check that delegateObject exists and that delegateObject has implemented a method to do the work asked of it.
To accomplish this, NSObject (which every Cocoa object inherits from) has this method:
- (BOOL)respondsToSelector:(SEL)aSelector
and objectA would do a simple test before sending a message to delegateObject, for example:
if ([delegate respondsToSelector: #selector(someMethod:sender:)])
{
[delegate someMethod:#"stuff" sender:self];
}
and because objectA only sends a message to its delegate if one's been assigned, delegate is not retained by objectA.
if we were to use UITableView as an example, it has a lot of UITableViewDelegate methods. One of them is:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
every time the user touches a row in a table, the UITableView object will first check that there's a delegate, if there's a delegate, it'll then check that the delegate has implemented the above method. If it does, then it'll send the message to the delegate. This method expects no return value, and UITableView will go about its merry way, regardless of what the delegate does. And if there is no delegate that implements that method, then nothing happens.