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.