2010-06-17 66 views
1
@implementation MySingletonClass 
static MySingletonClass *sharedInstance = nil; 


+ (MySingletonClass*)sharedInstance { 
    @synchronized(self) { 
     if (sharedInstance == nil) { 
      sharedInstance = [[self alloc] init]; 
     } 
    } 
    return sharedInstance; 
} 

+ (id)alloc { 
    @synchronized(self) { 
     if (sharedInstance == nil) { 
      sharedInstance = [super alloc]; 
      return sharedInstance; 
     } 
    } 
    return nil; 
} 

+ (id)allocWithZone:(NSZone *)zone { 
    @synchronized(self) { 
     if (sharedInstance == nil) { 
      sharedInstance = [super allocWithZone:zone]; 
      return sharedInstance; 
     } 
    } 
    return nil; 
} 

-(id)init { 
    self = [super init]; 
    if (self != nil) { 
     // initialize stuff here 
    } 

    return self; 
} 

@end 

不知道是否可以覆蓋alloc和allocWithZone:像這樣...?這個單身模式有意義嗎?

回答

1

你並不需要重寫頁頭,因爲默認的實現調用allocWithZone:比

其他,你可能需要重寫一些其他的方法。有關詳細信息,請參閱Apple docs