views:

89

answers:

3

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.

+7  A: 
- (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.

Chuck
This does not handle situations where the class is loaded by multiple (but different) classloaders. The singleton is only going to hold for a single classloader. If your code might run in a container, you might have it running in multiple JVM's and each one thinks it's the only one. It really depends on what you are trying to count/protect. Java isn't the cleanest choice when it comes to resource locking because of said classloader/JVM issue.
Kelly French
@Kelly: This isn't Java. It's Objective-C. I don't think the iPhone can even run Java.
Chuck
+3  A: 

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.

Kelly French
+2  A: 

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.

Bill K