How to send a message from a view controller to app delegate?
That’s a question that everybody asks who is trying to follow the model-view-controller paradigm. There is an easy way to access your app delegate from anywhere in your app.
The application delegate is the place to implement methods of the UIApplicationDelegateProtocol. For example didFinishLaunching when the launch process is done and you can take over control, or applicationWillTerminate to give you a chance of saving data before the application quits. It’s also a place where many people would put parts related to their model, data tables, database access and the like.
Cocoa Touch apps have one shared instance of the UIApplication class which has an instance method to retrieve a pointer to the app delegate. Since sharedApplication method is a class you can call it literally from ANYWHERE inside you code. Also because it is just two functions calls returning a pointer each you don’t have to worry too much about overhead.
// have imported the header for your app delegate class MyAppDelegateClass *appDelegate = [[UIApplication sharedApplication] delegate]; [appDelegate someMethod]; // anything defined in header
In the beginning I found myself copying the line above quite frequently. Most of the time I used it in the delegate methods of UITableView to gain access to the NSArray keeping my items which I wanted to display in the table.
Once my apps got bigger though that it made sense to move the model related code into their own engine class I did not need this any more because the game engine itself would also become a shared instance which I could access from anywhere I needed to.