2012-05-10 2 views
-1

처음 "Constants"를 사용할 때 초기화 할 수 있도록 "dataFilePath"를 정적 변수로 저장하고 [Constants SDataFilePath]와 같이 클래스를 인스턴스화 할 필요가 없습니다. 하지만 사실은 init 메소드가 호출되지 않는다는 것입니다. 내 요청에 어떻게 대처할 수 있습니까? (Java에서는 생성 메소드를 클래스에 액세스하기위한 첫 번째 호출 시간이라고합니다).정적 변수 초기화 방법

@implementation Constants 

static NSString *dataFilePath; 

-(id)init 
{ 
    NSLog(@"init!"); 
    if(self = [super init]) { 
     dataFilePath = [self getDataFilePathWithArg:dbfile]; 
    }  
    return self; 
} 

+(NSString *)SDataFilePath { 
    return dataFilePath; 
} 
.... 
@end 

답변

1

그럼 상수를 싱글 톤으로 만들 수 있습니다. 그것이 얼마나 코드를두고하는 .m에이 방법을 추가

+ (Constants *)sharedConstants 
{ 
    static Constants *_sharedConstants = nil; 
    static dispatch_once_t oncePredicate; 
    dispatch_once(&oncePredicate, ^{ 
     _sharedConstants = [[self alloc] init]; 
    }); 

    return _sharedConstants; 
} 

그리고 .H에 메소드 선언 :

+ (Constants *)sharedConstants; 

은 다음과 같이 당신의 변수에 액세스 :

[[Constants sharedConstants] SDataFilePath] 

처음으로 [Constants sharedConstants]에 액세스 할 때 init을 강제 실행합니다 (처음에만). 또한 + (NSString *) SDataFilePath를 클래스 메서드가 아닌 인스턴스 메서드로 변경해야합니다.

-(NSString *)SDataFilePath 
0

이렇게하면 안됩니다. 이 경로를 정적으로 유지하려는 이유는 무엇입니까? getter를 사용하여 dataFilePath를 설정하는 방법을 살펴볼 수는 있지만 setter는 없으며 클래스를 싱글 톤으로 인스턴스화해야 할 수도 있습니다. 그렇게하면 내부 메서드로 경로를 설정하고 인스턴스를 싱글 톤으로 공유 할 수 있습니다. here

을 참조하십시오.