I have an iOS application. Application has 2 different views: Main and Settings. In fact, application needs to load and initialize some library and framework before it is used in Main View.
When I put this initialization in viewDidLoad
method, it works OK. But when go to Settings and come back to Main View, initialization starts again, which is not what I want, and application results in a memory problem.
I need an method that is called once when application is started. Any idea?
EDIT: I switched to tabbed view. It loads views once. This is another solution.
Use this one:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
It should be in your appdelegate class.
Hope it helps
viewDidLoad
obviously it 'll be called for every time you load it, Here all you need is to remember whether you have opened it alresdy or not. for this you can maintain plist or NSUserDefault key value pair or even a global variable in the appDelegate
to remember the state... - iDroid 2012-04-04 06:58
You state in one of your comments that you don't want to put this code in application:didFinishLaunching
and you want to keep it in viewDidLoad. You can use this snippet to run your code only the first time is is invoked:
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
// code here
});
The inner block will only be executed once. If the view is loaded again, the block is not called. Note that there is an Xcode code snippet for this which you can access by starting to type dispatch_once
in the editor:
You can also use
+ [NSObject initialize]
Define a class method of that name, and it will be run once before any other messages are sent to that class:
+ (void)initialize {
// Put one-time initialization code here.
}
In your AppDelegate
, one of the objects guaranteed to have only one instance (singleton) throughout the app, you can declare an instance variable/property:
BOOL initialized;
And then in viewDidLoad
of your UIViewController
, you check if it's the code has been initialized; if not, then run the code and set the variable to true:
if (!initialized) {
// Code goes here
initialized = true;
}
didFinishlaunchingWithOptions
iDroid 2012-04-04 06:48