我已经习惯Java
并且目前正在学习过程中Objective-C
。
基本上我会这样创建Singleton
类Java
:
public class SingletonClass{
private static instance; //Step 1
public static SingletonClass getInstance(){ //Step 2
if(instance == null)
instance = new SingletonClass();
return instance;
}
}
很简单吧?
但是我发现很难为此创建直接解决方案 Objective-C
我确实是这样的:
@implementation SingletonClass(){
//I want to do step 1 here which is to make a private static instance;
//it is said that private variables are declared here
static SingletonClass *instance; //but it is said that static keyword is different here
}
//then I would do something like step 2
+ (id)getInstance{
if(instance == nil)
instance = self;
return instance;
}
@end
问题是有一个错误:Type name does not allow storage class to be specified
你们如何在Objective-C中进行简单的Singleton课程?
用途dispatch_once_t
:
从Apple文档中获取dispatch_once(3)
dispatch_once()函数提供了一种简单而有效的机制,可以仅一次运行一次初始化程序,类似于pthread_once(3)。
另请参阅:Mike Ash的dispatch_once的秘密
+(instancetype)sharedInstance
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[SingletonClass alloc] init];
});
return sharedInstance;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句