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.
Initialization is the process of locating and using the defined values for variable data that is used by a computer program. For example, an operating system or application program is installed with default or user-specified values that determine certain aspects of how the system or program is to function.
First method called during app launch 1) The app is launched, either explicitly by the user or implicitly by the system. 2) The Xcode-provided main function calls UIKit's UIApplicationMain() function. 3) The UIApplicationMain() function creates the UIApplication object and your app delegate.
Swift init() Initialization is the process of preparing an instance of a class, structure, or enumeration for use. This process involves setting an initial value for each stored property on that instance and performing any other setup or initialization that is required before the new instance is ready for use.
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:
Use this one:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
It should be in your appdelegate class.
Hope it helps
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.
}
https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/nsobject_Class/Reference/Reference.html#//apple_ref/occ/clm/NSObject/initialize
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With