Question

I want to class that should be initialized only once and returns some value which was computed the first time. Is below the right approach ?

@property (nonatomic, retain) NSString *userAgent;

@implementation UserAgent
@synthesize userAgent = _userAgent;


+ (NSString *) userAgentString
{
    UserAgent *thisClass;
    if(self == nil)
    {
        thisClass = [[UserAgent alloc] init];
    }

    if (thisClass.userAgent == nil)
    {
        return @"not initialized";
    }

    return thisClass.userAgent;
}
Was it helpful?

Solution

No.

  1. thisClass is a local variable. This means, the value will be reset (to garbage) everytime +userAgentString is called. At least make it static.

  2. self's meaning is not what you expect inside a class method. Do you mean thisClass?

  3. Even with the above fixes, the method isn't thread-safe, which may or may not be okay.

See Create singleton using GCD's dispatch_once in Objective C and Singleton in iOS 5? as examples to properly construct a singleton.

OTHER TIPS

A couple changes. First, thisClass should be static. Second, you don't have a self pointer in a static method, so you should be using thisClass there. Like so:

+ (NSString *) userAgentString
{
    static UserAgent *thisClass;
    if(thisClass == nil)
    {
        thisClass = [[UserAgent alloc] init];
    }

    if (thisClass.userAgent == nil)
    {
        return @"not initialized";
    }

    return thisClass.userAgent;
}

Also, a better approach might be to use a Singleton, as mentioned by a commenter.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top