2010-06-09 10 views
0

내 코드에서 SinglestonClass를 만들었지 만 문제가 있습니다. My 변수는 -init 메서드에서 초기화되지만 singlestonClass를 호출하면이 변수가 다시 초기화됩니다. 변수에 대해 단일 초기화를 만들 수 있습니까? 덕분에 .객관적인 c의 싱글 톤 클래스

@implementation SingletonController 

@synthesize arrayPosition; 
@synthesize arrayMovement; 

@synthesize actualPosition; 
@synthesize actualMove; 

@synthesize stopThread; 


+(SingletonController*)sharedSingletonController{ 

    static SingletonController *sharedSingletonController; 

    @synchronized(self) { 
     if(!sharedSingletonController){ 
      sharedSingletonController = [[SingletonController alloc]init]; 
     } 
    } 

    return sharedSingletonController; 
} 


//I don't want a re-initialization for these variables 
-(id)init{ 
    self = [super init]; 
    if (self != nil) { 
     arrayPosition = [[NSMutableArray alloc]init]; 
     arrayMovement = [[NSMutableArray alloc]init]; 

     actualPosition = [[Position alloc]init]; 
     actualMove = [[Movement alloc]init]; 

     stopThread = FALSE; 
    } 
    return self; 
} 


-(void) dealloc { 
    [super dealloc]; 
} 
@end 

답변

2

당신의 init 메소드는 당신의 싱글 톤 클래스를 제외하고 누구도 호출되어서는 안됩니다. 이것이 sharedSingletonController 메소드의 용도입니다. 이 클래스의 동일한 정적 인스턴스를 반환 할 책임이있는 팩터 리 메서드입니다. 나는 또한 당신이 당신의 싱글 톤 객체의 정적 인스턴스 나 sharedSingletonController 셀렉터 자체의 이름을 바꾸어 둘 사이의 명확성을 높이고 더 깨끗한 설계를 제안 할 것을 제안한다. 이 특별한 경우에는 코드를 읽어야하는 사람을 혼동시킬 수 있습니다.

싱글 톤 팩토리 메서드에서 클라이언트 코드가 어떻게 호출되는지 보지 않고도 문제가있는 부분을 해독하기가 어렵습니다. 어떻게 호출되는지를 포함하여 나머지 코드를 볼 필요가 있습니다. DO NOT DO

SingletonController *sigController = [SingletonController sharedSingletonController];

: 클라이언트 코드에서, 당신은 같은 것을 사용해야

SingletonController *sigController = [[SingletonController alloc] init];

코코아 기초 가이드에 대한 자세한 내용은 읽기 here.