我已经习惯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课程?
答案 0 :(得分:1)
使用dispatch_once_t
:
来自Apple文档dispatch_once(3)
dispatch_once()函数提供了一种简单有效的机制来运行初始化器一次,类似于pthread_once(3)。
另见:Mike Ash的Secrets of dispatch_once
+(instancetype)sharedInstance
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[SingletonClass alloc] init];
});
return sharedInstance;
}
答案 1 :(得分:-3)
它们在目标c中被称为外部变量。
在#import put
下的app delegate中NSString *singleton;
然后在任何类(视图控制器)中你想在它的.h文件中使用它
extern NSString *singleton;