Posts Tagged ‘AppDelegate’
Usually, iPhone apps are built using some kinda hierarchy:
- ->AppDelegate
- ->-> RootViewController
- ->->->OtherViewController(s)
- ->->->->Views
On various occasions, you might want to get some information from your AppDelegate (e.g. values, array infos, etc…).
You might already know, that there is a simple line of code, which gives you access to your AppDelegate:
AppDelegate *mainDelegate = (AppDelegate*)[[UIApplication sharedApplication]delegate];
If you need access to your AppDelegate only once or twice in a View or ViewController, this is the best way to go. However, if you have several methods in your View or ViewController and some of them need AppDelegate access, you always have to repeat the above line of code first.
In order to avoid that, there is a simple way, to permanently implement AppDelegate access in your View or ViewController:
//this example assumes, that we are using a ViewController
//inside .h file
//below #import lines
@class AppDelgate;
@interface MyViewController : UIViewController {
AppDelegate *mainDelegate;
}
//@property (nonatomic, retain) AppDelegate *mainDelegate; //error correction here - no need to @property
@end
//inside .m file
//below #import lines
#import "AppDelegate.h"
@implementation MyViewController
@synthesize mainDelegate;
- (void)viewDidLoad {
mainDelegate = (AppDelegate*)[[UIApplication sharedApplication]delegate];
}
- (void)dealloc {
//[mainDelegate release]; //error correction here - the mainDelegate object does not need to be released, since we do not call alloc init on it.
[super dealloc];
}
//now you have access to your AppDelegate in every method
//example: we assume, that our AppDelegate holds three different integer values we want to grab
- (void)methodA {
int numberA = mainDelegate.numberA;
}
- (void)methodB {
int numberB = mainDelegate.numberB;
}
- (void)methodC {
int numberC = mainDelegate.numberC;
}
As you can see, it’s slightly more work to implement AppDelegate access than just using that single line of code over and over again. However, in my opinion it’s well worth the time, especially if your .m file holds many methods.
Your code appears much cleaner that way.
