简体   繁体   中英

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? Maybe there is also an better way, instead of measuring how many times this method was called, and storing that in an 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM