Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
404 views
in Technique[技术] by (71.8m points)

objective c - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...