13

I don't know when or why I should use [[UIApplication sharedApplication] delegate]

I use delegate when [self.navigationController pushViewController:myView Animation:YES] does't navigate. I make MyView *delegate = [[UIApplication sharedApplication] delegate] and [delegate pushViewController:myView Animation:YES] to make the navigation work correctly.

I don't know if the solution is correct and in addition I don't know what is the use for [[UIApplication sharedApplication] delegate] or what are its effects on the application.

Can someone help me?

Thanks!!

mfaani
  • 33,269
  • 19
  • 164
  • 293
rasputin
  • 241
  • 1
  • 4
  • 13
  • Check the delegate outlet of UIApplication in Interface Builder. It looks like it is connected to a navigation controller, which doesn't seem to be OK. – Costique Nov 25 '10 at 13:13

2 Answers2

22

[[UIApplication sharedApplication] delegate] will give you a pointer to your app delegate. the one that was automatically created when you made the project. Usually it's named YourAppNameAppDelegate.

two things are a little wrong with your code.

  1. when you declare MyView *delegate this should either be id delegate or YourAppNameAppDelegate *delegate.

  2. You shouldn't have to access your navigationController via the app delegate. I would look into why self.navigationController is failing, and address that. You're basically implementing a singleton pattern when you rely on the app delegate. Because the singleton pattern is the least cool programming design pattern, it won't win you any points when talking shop with other programmers.

Kenny Winker
  • 11,919
  • 7
  • 56
  • 78
  • Thank you very much for your response!! but I don't understand when I can need use a pointer to the app delegate. Where are the self.navigationController address that you would look? – rasputin Nov 26 '10 at 00:14
4
self.appDelegate = [[UIApplication sharedApplication] delegate];

When you create a variable called appDelegate in your IVars, it won't just get set automagically to the app delegate - you have to set it yourself. From ANYWHERE in your application, you can access the delegate by the application singleton.

[UIApplication sharedApplication] <--- gives access to the singleton

delegate method returns a pointer to the app delegate.

So, since your variables needed to be initialized, there are two logical places to do it - one is in the initializer if you create one or in a method that is called at near the beginning of the use of a view and its controller and that place is in viewDidLoad.

benhowdle89
  • 36,900
  • 69
  • 202
  • 331