static method objective c - init once
-
04-06-2021 - |
質問
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 itstatic
.self
's meaning is not what you expect inside a class method. Do you meanthisClass
?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.
他のヒント
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.
http://www.galloway.me.uk/tutorials/singleton-classes/
This worked..Thanks @Inafziger