一千萬個為什麽

搜索

Singleton類的實現

我一直在使用appDelegate類作為全局變量但是最近我開始知道它不是保持全局變量的gud方式所以我試圖使一個單例類如下

@implementation globalVar


static globalVar *_sharedInstance =nil;

@synthesize totalTime;
- (id) init
{
    if (self = [super init])
    {


    }
return self;
}

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

    return _sharedInstance;
}
+ (id)allocWithZone:(NSZone *)zone {
    @synchronized(self) {
        if (_sharedInstance == nil) {
            _sharedInstance = [super allocWithZone:zone];
            return _sharedInstance;
        }
    }
    return nil;
}
- (id)copyWithZone:(NSZone *)zone
{
    return self;
}
-(NSUInteger)retainCount
{
    return NSUIntegerMax;  //denotes an object that cannot be released
}
- (void)release
{
   //do nothing
}

- (id)autorelease

{
    return self;
}


- (void) setTotalTime:(NSString *)time
{

    @synchronized(self) {
        if (totalTime != time) {
            [totalTime release];
            totalTime = [NSString stringWithFormat:@"%@",time];
        }
    }

    //NSLog(@"time %@",totalTime);
}
-(NSString *)getTotalTime
{
    @synchronized(self) {
        //NSLog(@"total %@",totalTime);
        return totalTime;
    }
}

當我在appDelegate類中設置totaltime的值並在該類中檢索它時,我只得到正確的值。但是當我只檢索其他類中的值時,我得到了BAD EXCESS。我首先創建sharedinstance然後只調用此方法然後為什麽我得到這個錯誤?

globalVar *myEngine = [globalVar sharedInstance];

NSLog(@"about %@",[myEngine totalTime]);

在我的應用程序委托中

globalVar *myEngine = [globalVar sharedInstance];

[myEngine setTotalTime:totalTime];

NSLog(@"in app delegate%@",[myEngine getTotalTime]);

最佳答案