如何在Objective C中创建直接的Singleton类?

时间:2014-08-01 02:38:22

标签: objective-c singleton

我已经习惯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课程?

2 个答案:

答案 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;