NOrder
NOrder

Reputation: 2493

How to use a class variable?

I have a class method loadImage:(NSString *)pathto load image from path, if the path is nil, the load the default path image.

 +(NSImage *) loadImage:(NSString *)path{
   if(path== nil){
    path = [[NSBundle mainBundle] pathForResource:@"default" ofType:@"png"];
  }
}

because the default path is always using the same path, I want to calculate the path only once if I run the method 1000 times, like

if(defaultPath == nil){
    defaultPath = [[NSBundle mainBundle] pathForResource:@"default" ofType:@"png"];
}
path = defaultPath;

, I think I can use static variable, but I don't know how to do it, please help me, I'm glad to know any suggestions about improving performance.

Upvotes: 0

Views: 88

Answers (2)

Monolo
Monolo

Reputation: 18253

There is a useful pattern based on GCD which handles this sort of situation nicely:

+(NSImage *) loadImage:(NSString *)path{

    static NSString *storedPath;

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        storedPath = [[NSBundle mainBundle] pathForResource:@"default" ofType:@"png"];
    });

    // Do whatever you need to do with the default resource path.
}

dispatch_once does exactly what you are after - it ensures that the initialization code is run only once. It is also thread safe.

Xcode's code completion even helps you use the pattern - if you start typing dispatch_once then you'll get the onceToken template directly.

Upvotes: 1

zoul
zoul

Reputation: 104065

Simply use a static variable to hold the default path:

static NSString *defaultPath = …;
if (path == nil) {
   path = defaultPath;
}

But if you're doing it for performance reasons, first make sure it's worth it. Most probably it's a premature optimization that's not worth the trouble.

Upvotes: 3

Related Questions