Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making some code only run once

I have some code that I would like to run only once in my MainViewController. It should run every time the user starts the app, but only after the MainViewController has loaded.

I don't want to run it in -(void)applicationDidFinishLaunching:(UIApplication *)application.

Here's the idea I had:

MainViewController.h

@interface IpadMainViewController : UIViewController <UISplitViewControllerDelegate> {     BOOL hasRun; }  @property (nonatomic, assign) BOOL hasRun; 

MainViewController.m

@synthesize hasRun;  -(void)viewDidLoad {     [super viewDidLoad];     if (hasRun == 0) {         // Do some stuff         hasRun = 1;     } } 

Any ideas?

like image 579
Jezen Thomas Avatar asked Mar 05 '12 18:03

Jezen Thomas


People also ask

How do you call a method only once on Android?

putBoolean("key",1); //or you can also use editor. putString("key","value"); editor. commit(); After doing so, say for example if user recalls an activity, then you check the value of in the shared prefs and if it is found, then just perform the action you wish to do else, allow the user to continue with the activity.

Which function is executed first when we start the program and Cannot be called again?

The main function serves as the starting point for program execution. It usually controls program execution by directing the calls to other functions in the program.


1 Answers

Swift 1,2:

static var token: dispatch_once_t = 0  dispatch_once(&token) {   NSLog("Do it once") } 

Objective-C

static dispatch_once_t once; dispatch_once(&once, ^ {   NSLog(@"Do it once"); }); 

Swift 3,4:

dispatch_once is no longer available in Swift. In Swift, you can use lazily initialized globals or static properties and get the same thread-safety and called-once guarantees as dispatch_once provided Apple doc

let myGlobal = { … global contains initialization in a call to a closure … }() _ = myGlobal  // using myGlobal will invoke                // the initialization code only the first time it is used. 
like image 148
Andrey Avatar answered Oct 13 '22 20:10

Andrey