开发者

Imlementation of Singleton Class

i have been using mostly the appDelegate class for global variables but recently i came to know that its not a gud way for keeping global variables so i am trying to make a singleton class as following

@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 *)getTo开发者_如何学运维talTime
{
    @synchronized(self) {
        //NSLog(@"total %@",totalTime);
        return totalTime;
    }
}

when i set the value for totaltime in my appDelegate class and retrieve it in that class only i get the correct value. but when i only retrieve the value in some other class i get BAD EXCESS. i first create the sharedinstance and then only call this method then why am i getting this error??

globalVar *myEngine = [globalVar sharedInstance];

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

in my app delegate

globalVar *myEngine = [globalVar sharedInstance];

[myEngine setTotalTime:totalTime];

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


You're releasing totalTime but not retaining the new value, which means that when you access it it's already been released, causing a bad access exception.

You can correct this by changing the line where you set the value to include a call to retain:

totalTime = [[NSString stringWithFormat:@"%@",time] retain];


Have a look at the discussion here:

Is it good practice to use AppDelegate for data manipulation and Handling?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜