Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run code only once [duplicate]

I cant figure out how to run a part of code in ViewDidLoad() method only once. I don't want that part of the code to be executed until the app is started again. Thanks for any help!

like image 826
motox Avatar asked Nov 29 '22 15:11

motox


2 Answers

You can use dispatch_once in your viewDidLoad:

static dispatch_once_t once;
dispatch_once(&once, ^
{
    // Code to run once
});

This will make the code run only once until you exit and close your app.

like image 181
Aluminum Avatar answered Dec 17 '22 00:12

Aluminum


You can also set up a BOOL flag to check whether the code has executed.

set up the bool above the implementation in the .m file:

static BOOL codeExecuted = NO;

in the -viewDidLoad() method:

if (!codeExecuted)
{

    //run code
    codeExecuted = YES;

}
like image 44
ZeMoon Avatar answered Dec 16 '22 22:12

ZeMoon