Objective c 如何在Objective C中创建直接的单例类?
我习惯于Objective c 如何在Objective C中创建直接的单例类?,objective-c,singleton,Objective C,Singleton,我习惯于Java,目前正在学习Objective-C 基本上,我会在Java中创建Singleton类,如下所示: public class SingletonClass{ private static instance; //Step 1 public static SingletonClass getInstance(){ //Step 2 if(instance == null) instance = new SingletonClass(); re
Java
,目前正在学习Objective-C
基本上,我会在Java
中创建Singleton
类,如下所示:
public class SingletonClass{
private static instance; //Step 1
public static SingletonClass getInstance(){ //Step 2
if(instance == null)
instance = new SingletonClass();
return instance;
}
}
@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
非常简单,对吗
但我发现在Objective-C
我喜欢这样:
public class SingletonClass{
private static instance; //Step 1
public static SingletonClass getInstance(){ //Step 2
if(instance == null)
instance = new SingletonClass();
return instance;
}
}
@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
问题是存在错误:类型名称不允许指定存储类
你们如何在Objective-C中创建直接的单例类?使用
dispatch\u once\t
:
来自苹果文档函数的dispatch_once()提供了一种简单有效的机制,可以精确地运行初始化程序一次,类似于pthread_once(3) 另见:迈克·阿什
+(instancetype)sharedInstance
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[SingletonClass alloc] init];
});
return sharedInstance;
}
它们在目标c中称为外部变量 #导入put下的应用内委托
NSString *singleton;
然后在任何一个类(视图控制器)中,您希望在的.h文件中使用它
extern NSString *singleton;
谷歌。谢谢我看一下。如果你不喜欢那一个,还有很多。看右边的相关问题列表。在你提交问题之前,这些问题也会出现。在发布之前回顾这些内容总是一个好主意。:)对不起,我是Objective-C的新员工,您能解释一下关于
dispatch\u once\t
?谢谢,回答得好。顺便说一句,很抱歉回复太晚,我不得不阅读你给出的链接。我还想对@rmaddy的评论给予赞扬,因为他的链接(stackoverflow.com/questions/5720029/…)很有帮助。这与创建singleton无关。