When use [[UIApplication sharedApplication] delegate]

rasputin picture rasputin · Nov 25, 2010 · Viewed 34.8k times · Source

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!!

Answer

Kenny Winker picture Kenny Winker · Nov 25, 2010

[[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.