我有一些代码,我想在我的MainViewController中只运行一次.它应该在用户每次启动应用程序时运行,但仅在MainViewController加载后运行.
我不想运行它-(void)applicationDidFinishLaunching:(UIApplication *)application.
这是我的想法:
MainViewController.h
@interface IpadMainViewController : UIViewController <UISplitViewControllerDelegate> {
BOOL hasRun;
}
@property (nonatomic, assign) BOOL hasRun;
Run Code Online (Sandbox Code Playgroud)
MainViewController.m
@synthesize hasRun;
-(void)viewDidLoad {
[super viewDidLoad];
if (hasRun == 0) {
// Do some stuff
hasRun = 1;
}
}
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?
我想每个实例只运行一次代码块.
我可以将dispatch_once_t谓词声明为成员变量而不是静态变量吗?
从GCD参考资料中,我不清楚.
谓词必须指向存储在全局或静态范围内的变量.使用具有自动或动态存储的谓词的结果是未定义的.
我知道我可以使用dispatch_semaphore_t和一个布尔标志来做同样的事情.我只是好奇.
我使用常规模式实现了单例对象.我的问题是:是否可以将此对象设置为nil,以便在以后调用[MySingleton sharedInstance]时对象被重新初始化?
// Get the shared instance and create it if necessary.
+ (MySingleton *)sharedInstance {
static dispatch_once_t pred;
static MySingleton *shared = nil;
dispatch_once(&pred, ^{
shared = [[MySingleton alloc] init];
});
return shared;
}
// We can still have a regular init method, that will get called the first time the Singleton is used.
- (id)init
{
self = [super init];
if (self) {
// Work your initialising magic here as you normally would
}
return self;
}
Run Code Online (Sandbox Code Playgroud)
我的猜测是 …