Wednesday, December 22, 2010

Local Static Variable Lifetime Expectation in Objective-C

Something I learned today, worth remembering for performance reasons. Static variable defined inside a method is actually a global variable, which is visible only inside that method!

What this means is that you can increase your method performance by declaring variable only once and reuse it when needed next time.

 Here's example code:
+ (NSString *)numberAsString:(NSUInteger *)aNumber
{
    static NSArray *myNumbers = nil;
    if (!myNumbers)
    {
        myNumbers = [[NSArray alloc] initWithObjects:
                     @"nolla", @"yksi",
                     @"kaksi", nil];
    }
    return [myNumbers objectAtIndex:aNumber];
}
If you move static variable definition outside of all methods, it will be available for everyone within the class. This is the "normal" use case for static variables.

2 comments:

  1. Hi Jouni,
    What happened , if a class contains all static methods, i have a class which contain near about 100 methods definition,as i know that static methods loads in memory all times, so they take a lot of memory,

    Please guide , am i correct?

    ReplyDelete
  2. I would suggest trying to redesign that class, 100 methods sounds like all-in-one problem. Try to split it into smaller pieces, which logically belong together.

    Otherwise I wouldn't worry about such things - until there really are problems. Unlike many mobile operating systems, iOS is pretty developer friendly. No much control, but usually things work ok :)

    ReplyDelete