[英]What's the easiest way to determine inside a method if it has been called the first time since app start?
I have a method where I do some startup animations. 我有做一些启动动画的方法。 The method gets called many times during usage of the app, but on it's first call it needs to do some special things in addition.
在应用程序使用过程中,该方法被调用了很多次,但是在第一次调用时,它还需要做一些特殊的事情。
Are Singletons the way to go? Singletons可以走吗? Maybe there is also an better way, instead of measuring how many times this method was called, and storing that in an ivar.
也许还有更好的方法,而不是测量此方法被调用的次数并将其存储在ivar中。
- (void)someMethod {
static BOOL hasBeenCalledBefore = NO;
if (!hasBeenCalledBefore) {
// perform setup
hasBeenCalledBefore = YES;
}
// do other stuff
}
Extra work may be required if you're using threads, but that's the basic idea. 如果使用线程,可能需要额外的工作,但这是基本思想。
Why isn't that initialization code in the constructor? 为什么构造函数中没有初始化代码? Maybe you need to factor that method out into it's own class which uses the constructor to handle the init block you mention.
也许您需要将该方法分解到它自己的类中,该类使用构造函数来处理您提到的init块。
An amendment to chuck's answer (pretty much correct) 对查克答案的修正(非常正确)
His works and answers your question, but another option you could use (assuming it didn't need access to any of the variables being passed to that method) would be to take the code out of your method and put it in a static initializer. 他的工作可以回答您的问题,但是您可以使用的另一种选择(假设它不需要访问传递给该方法的任何变量)将代码从您的方法中取出并放入静态初始化器中。 It will only be executed when the class is first loaded and will isolate what is essentially completely different pieces of code.
它仅在首次加载该类时执行,并将隔离本质上完全不同的代码段。
If you want it called for every new class, use Chuck's answer but with a member variable, or use a class initializer. 如果希望每个新类都调用它,请使用Chuck的答案但要带有成员变量,或者使用类初始化程序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.