43

I'm writing my first iPhone application and I'm having trouble switching views. I have 2 views and a reference to each in the AppDelegate (an instance of UIApplicationDelegate). I create instances of both in the applicationDidFinishLaunching and immediately show the first view. This works fine.

The problem is the reference to the other view is in the AppDelegate and I can't figure out how to get a reference to it so I can switch to the other view. Is there a way to get a reference to the main UIApplication or UIApplicationDelegate objects?

Bartłomiej Semańczyk
  • 59,234
  • 49
  • 233
  • 358
derGral
  • 1,836
  • 4
  • 19
  • 29

2 Answers2

109

Yes, UIApplication is a singleton, and uses the normal singleton pattern for Objective-C:

[UIApplication sharedApplication];

You can get your delegate class directly from it:

MyAppDelegate *delegate = (MyAppDelegate *)[[UIApplication sharedApplication] delegate];
Kerem Baydoğan
  • 10,475
  • 1
  • 43
  • 50
Louis Gerbarg
  • 43,356
  • 8
  • 80
  • 90
  • 1
    it may be obvious but worth noting that MyApplicationDelegate is the name of the class that conforms to the protocol **UIApplicationDelegate**, in many cases **AppDelegate** – Mehdi Ijadnazar Nov 05 '15 at 14:45
  • I am trying this but getting errors. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate]; 'sharedApplication' is unavailable: not available on iOS (App Extension) - Use view controller based solutions where appropriate instead. – Akbar Khan Jul 04 '21 at 17:50
19

Use:

[[UIApplication sharedApplication] delegate];
Codebeef
  • 43,508
  • 23
  • 86
  • 119