views:

1322

answers:

2

I'm just beginning to work on iPhone apps. How do I know when I should be putting stuff in the appdelegate versus a custom class? It there a rule or any type of analogy with another programming language like python or php that uses an appdelegate?

Thanks...

+3  A: 

Your application delegate is the heart of your application. It's effectively your "Program Controller".

The Application Delegate is the class that receives application-level messages, including the applicationDidFinishLaunching message most commonly used to initiate the creation of other views.

While not exactly similar you could think of it as the "main()" routine of your Cocoa program.

Andrew Grant
+13  A: 

I normally avoid the design approach implied by Andrew's use of the term "heart of your application". What I mean by this is that I think you should avoid lumping too many things in a central location -- good program design normally involves separating functionality by "area of concern".

A delegate object is an object that gets notified when the object to which it is connected reaches certain events or states. In this case, the Application Delegate is an object which receives notifications when the UIApplication object reaches certain states. In many respects, it is a specialized one-to-one Observer pattern.

This means that the "area of concern" for the AppDelegate is handling special UIApplication states. The most important of these are:

  • applicationDidFinishLaunching: - good for handling on-startup configuration and construction
  • applicationWillTerminate: - good for cleaning up at the end

You should avoid putting other functionality in the AppDelegate since they don't really belong there. Such other functionality includes:

  • Document data -- you should have a document manager singleton (for multiple document applications) or a document singleton (for single document applications)
  • Button/table/view controllers, view delegate methods or other view handling (except for construction of the top-level view in applicationDidFinishLaunching:) -- this work should be in respective view controller classes.

Many people lump these things into their AppDelegate because they are lazy or they think the AppDelegate controls the whole program. You should avoid centralizing in your AppDelegate since it muddies the areas of concern in the app and doesn't scale.

Matt Gallagher
Matt, the last sentence doesn't make sense.
Abizern
Sorry about that, Abizern. I've fixed the wording, now.
Matt Gallagher