iOS function to be called once (when application is initialized)

mert picture mert · Apr 4, 2012 · Viewed 7.7k times · Source

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.

Answer

Mike Weller picture Mike Weller · Apr 4, 2012

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:

enter image description here

enter image description here