本文介绍了制作一些代码只运行一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一些代码,我想在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:
在Swift中不再提供dispatch_once。在Swift中,你可以使用延迟初始化的全局变量或静态属性,并获得相同的线程安全和一次性保证,因为dispatch_once提供了 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.
更多推荐
制作一些代码只运行一次
发布评论