0

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;
}
Lou Franco
  • 87,846
  • 14
  • 132
  • 192
i_raqz
  • 2,919
  • 10
  • 51
  • 87
  • 3
    Search for information on singleton's for a good example of how to do this. – lnafziger May 01 '12 at 18:04
  • 1
    add static before UserAgent *thisClass and you should be fine. `static UserAgent *thisClass;` – Jonathan Cichon May 01 '12 at 18:04
  • possible duplicate of [Thread safe instantiation of a singleton](http://stackoverflow.com/questions/2199106/thread-safe-instantiation-of-a-singleton) – Chuck May 01 '12 at 18:06

3 Answers3

3

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.

Community
  • 1
  • 1
kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
  • @i_raqz: which is the same as the first answer of http://stackoverflow.com/questions/8796529/singleton-in-ios-5. – kennytm May 01 '12 at 18:19
0

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.

Eric Petroelje
  • 59,820
  • 9
  • 127
  • 177
0

http://www.galloway.me.uk/tutorials/singleton-classes/

This worked..Thanks @Inafziger

mattjgalloway
  • 34,792
  • 12
  • 100
  • 110
i_raqz
  • 2,919
  • 10
  • 51
  • 87