싱글 톤 클래스의 멤버를 초기화하는 가장 좋은 장소는 어디입니까?코코아 - 싱글 톤 객체 : 멤버 변수 초기화 위치?
저는 Apple 기본 가이드 싱글 톤 구현을 사용하고 있습니다. 당신은 inits가 어떤 라인에서 일어 났는지 정확하게 지적 해 주시겠습니까? 코드는 다음과 같다 :
static MyGizmoClass *sharedGizmoManager = nil;
+ (MyGizmoClass*)sharedManager
{
@synchronized(self) {
if (sharedGizmoManager == nil) {
[[self alloc] init]; // assignment not done here
}
}
return sharedGizmoManager;
}
+ (id)allocWithZone:(NSZone *)zone
{
@synchronized(self) {
if (sharedGizmoManager == nil) {
sharedGizmoManager = [super allocWithZone:zone];
return sharedGizmoManager; // assignment and return on first allocation
}
}
return nil; //on subsequent allocation attempts return nil
}
- (id)copyWithZone:(NSZone *)zone
{
return self;
}
- (id)retain
{
return self;
}
- (unsigned)retainCount
{
return UINT_MAX; //denotes an object that cannot be released
}
- (void)release
{
//do nothing
}
- (id)autorelease
{
return self;
}
http://boredzo.org/blog/archives/2009-06-17/doing-it-wrong을 읽고 싶을 수도 있습니다. 릴리스를 무시하는 싱글 톤을 정말로 원하십니까? 그냥 버그를 가린다. –
그리고 Jon Hess가 Apple 문서를 따르고 있음을 상기시키기 전에 : Apple 문서에 대한 응답으로이 게시물을 작성했습니다. –
또한 유의할 점은 클래스에는 모든 종류의 "멤버"가 없다는 것입니다. 얻을 수있는 가장 가까운 클래스의 구현 파일에 정적 변수입니다. 그리고 클래스 멤버는 초기화하려는 것이 아닙니다. 당신이 말하고자하는 것은 싱글 톤 * 인스턴스의 * 인스턴스 * 변수입니다. –