制作一些代码只运行一次

编程入门 行业动态 更新时间:2024-10-28 01:15:48
本文介绍了制作一些代码只运行一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一些代码,我想在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.

更多推荐

制作一些代码只运行一次

本文发布于:2023-05-27 19:34:30,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/300596.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:代码

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!