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;
}
No.
thisClass
is a local variable. This means, the value will be reset (to garbage) everytime +userAgentString
is called. At least make it static
.
self
's meaning is not what you expect inside a class method. Do you mean thisClass
?
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.