1

init メソッドは NSObject クラスで宣言されているため、クライアント コードはシングルトン クラスの新しいインスタンスを作成できます。クライアントが新しいインスタンスを作成できないような実際のシングルトンを実現する方法はありますか。

4

4 に答える 4

1

これを行うだけです:

 static SingletonClass  *singleton;

+ (SingletonClass *)sharedInstance 
 {
     @synchronized(self) { //For thread safety
         if (singleton == nil) {
           [[self alloc] init];
         }
         return singleton;
      }
 }


  -(id)init
   {
      if (singleton) { //This way init will always return the same instance
         return singleton;
       }
       self = [super init];
       if (self) {
           singleton = self; 
       }
       return singleton;

   }
于 2012-10-19T17:38:22.400 に答える
0

これは、ObjectiveCでシングルトンを実行するための適切な方法です。

+ (id)sharedManager
{
    static dispatch_once_t onceQueue;
    static SingletonObjectClass *singleton = nil;

    dispatch_once(&onceQueue, ^{
        singleton = [[self alloc] init];
    });

    return singleton;
}

- (id)init {
    self = [super init];
    if (self) {
       //.....
    }
   return self;
}
于 2012-10-19T18:10:50.837 に答える
-1

init メソッドは、インスタンス変数の初期化用です。単独ではオブジェクトを作成しません。実際の 1 トンを達成するには、割り当て、コピー メソッドをオーバーライドする必要があります。

これが明確になることを願っています。

+ (id)alloc {
    NSLog(@"%@: use +sharedInstance instead of +alloc", [[self class] name]);
  return nil; 
}
+ (id)new {
 return [self alloc];
}

+ (SingletonClass *)sharedInstance {
static SingletonClass *myInstance = nil; 
 if (!myInstance)
 {
    myInstance = [[super alloc] init];
 }
 return myInstance; 
}
于 2012-10-19T13:03:53.447 に答える
-1

クラスの静的オブジェクトを毎回返して、シングルトンにすることができます。

@implementation Singleton
@synthesize testVar;

+ (Singleton*) sharedObject {
    static Singleton * myInstance = nil;
    if (myInstance == nil) {
        myInstance = [[[self class] alloc] init];
        testVar = 5;
        // Set default values if needed
    return myInstance;
}

オブジェクトとそのメンバーにアクセスするには:

[[Singleton sharedObject] testVar]
于 2012-10-19T13:04:14.267 に答える