I'm looking to be able to reference certain state/objects through anywhere in my application. For instance, a user logs in to their application, I need to call a web service and retrieve the users information. Then I want to be able to access this information from anywhere in the application with something like the following:
myAppDelegate *delegate = [[UIApplication sharedApplication] delegate]; user = delegate.u;
Is setting an instance variable as a User object in the app delegate and referencing it from there when needed a poor way of going about it? I typically set it there upon the user's login.
Wanted to hear how the pros handle this one.
Overview. Your app delegate object manages your app's shared behaviors. The app delegate is effectively the root object of your app, and it works in conjunction with UIApplication to manage some interactions with the system.
AppDelegate is responsible for handling application-level events, like app launch and the SceneDelegate is responsible for scene lifecycle events like scene creation, destruction and state restoration of a UISceneSession.
A delegate is an object that acts on behalf of, or in coordination with, another object when that object encounters an event in a program. The delegating object is often a responder object–that is, an object inheriting from NSResponder in AppKit or UIResponder in UIKit–that is responding to a user event.
Normally, you should only connect things to the app delegate if they:
For everything else, you should create a singleton which manages access to them.
Jason Coco suggested routing through the Application Controller. In my programs I normally avoid this, as I think it puts too much responsibility at the top level -- I think things should self-manage where possible and that higher level management should only be used when there is a requirement for coordination between peer-level modules.
I'm not going link my own blog but if you Google me and singletons you'll probably find a post I wrote going into more detail.
Matt is a bit too modest. His posting on the subject is one of the best I have read, and deserves a link. http://cocoawithlove.com/2008/11/singletons-appdelegates-and-top-level.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With