本文介绍了制作一些代码只运行一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些代码,我想在MainViewController中只运行一次。它应该在用户每次启动应用程序时运行,但仅在MainViewController加载后运行。

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.

我不想在中运行它 - (void)applicationDidFinishLaunching:(UIApplication *)application

这是我的想法:

MainViewController.h

MainViewController.h

@interface IpadMainViewController : UIViewController <UISplitViewControllerDelegate> {
    BOOL hasRun;
}

@property (nonatomic, assign) BOOL hasRun;

MainViewController.m

MainViewController.m

@synthesize hasRun;

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

任何想法?

推荐答案

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:



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.

这篇关于制作一些代码只运行一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-16 23:46