单实例的类的实现

单实例的类的一个重要作用就是用于维护全局的的信息,它的实现类似乎下面:

 

//*****************头文件BasicInfoManager.h****************

#import

 

@interface BasicInfoManager : NSObject {

NSString *appUserName;  //需要管理的全局信息

}

 

@property (nonatomic, retain) NSString *appUserName;

 

+ (id)sharedManager;

+ (void)attemptDealloc;

 

@end

 

 

 

//*****************实现文件BasicInfoManager.m****************

#import "BasicInfoManager.h"

 

static BasicInfoManager *manager = nil

 

@implementation BasicInfoManager

 

@synthesize appUserName;

 

+ (id)hiddenAlloc{

return [super alloc];

}

 

+ (id)sharedManager{

if (manager == nil) {

manager = [[[self class] hiddenAlloc] init];

}

return manager;

}

 

+ (id)alloc {

NSLog(@"%@: use +sharedInstance instead of +alloc", [[self class] description]);

return nil;

}

 

+ (id)new {

return [self alloc];

}

 

+ (id)allocWithZone:(NSZone *)zone {

return [self alloc];

}

 

- (id)copyWithZone:(NSZone *)zone {

NSLog(@"BasicInfoManager: attempt to -copy may be a bug."); 

[self retain]; 

return self;

}

 

- (id)mutableCopyWithZone:(NSZone *)zone {

return [self copyWithZone:zone];

}

 

+ (void)attemptDealloc {

if ([manager retainCount] != 1

return

[manager release]; 

manager = nil;

}

 

+ (BOOL)sharedManagerExists {

extern BasicInfoManager *manager;

r eturn (nil != manager);

}

 

- (void)dealloc{

[appUserName release];

[super dealloc];

}

 

@end

你可能感兴趣的:(iPhone开发)