2010-06-17 36 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