Fire Fist
Fire Fist

Reputation: 7050

How many times i need to declare UIApplication SharedApplication in my class in iOS?

In my iOS app , i need to access some data from AppDelegate. So i used like that

- (void)ViewDidLoad
{
    self.app = [[UIApplication sharedApplication] delegate];
    [self.app.arrayFromApp addObjects:self.myArray];
    [self.app loadSomething];
}

I want to know Is this enough when i declared above code One time in ViewDidLoad and i can access from everywhere (Methods,variable,etc...) in this class?.

Or

Do i need to declare that code every method when i have to access data from AppDelegate?.

example.

- (void)methodOne
{
 self.app = [[UIApplication sharedApplication] delegate];
 self.app.isTrue = self.isTrueOrNot;
}

- (void)methodTwo
{
 self.app = [[UIApplication sharedApplication] delegate];
 [self.app loadSomething];
}

Thanks for your help.

Upvotes: 0

Views: 285

Answers (3)

Florian
Florian

Reputation: 5405

I would suggest making app a readonly property and instantiate it lazily.

@interface ViewController : UIViewController

@property (readonly, nonatomic) AppDelegate *app;

@end


@implementation ViewController

@synthesize app = _app;

- (AppDelegate *)app
{
    if (_app == nil) {
        _app = [[UIApplication sharedApplication] delegate];
    }
    return _app;
}
@end

Upvotes: 1

ahwulf
ahwulf

Reputation: 2584

Another option is to define this in your appdelegate.h file

#define APPLICATION ((AppDelegate*)([UIApplication sharedApplication].delegate))

Just a shorthand.

Upvotes: 1

nsgulliver
nsgulliver

Reputation: 12671

yes it is enough one time in your class to declare if you are using app as class level ivar

 self.app = [[UIApplication sharedApplication] delegate];

You don't need to declare it within every method if you are declaring app as a property in your class

Upvotes: 2

Related Questions