Singleton uses in multi-thread

I have used Singleton for a long time, but today I find a strange things that the singleton object will 'autorelease'? And will cause the App crash next time try to call singleton object.

 

Finally I find that because I raise new thread in this class. With normal singleton class definination:

 

 

+ (DataAccessConroller *)sharedController {
	@synchronized([DataAccessConroller class]) {
		if (!_sharedController) {
			_sharedController=[[self alloc] init];
		}
		return _sharedController;
	}
	return nil;
}

/* 
 The Methods should not changed. 
 */

+ (id)alloc {
	@synchronized([DataAccessConroller class]) {
		_sharedController = [super alloc];
		return _sharedController;
	}
	
	return nil;
} 

- (id)init {
	self = [super init];
	if (self) {
        xxxx
	}
	return self;
}

+ (id)allocWithZone:(NSZone *)zone {
	@synchronized([DataAccessConroller class]) {
		_sharedController= [super allocWithZone:zone];
		return _sharedController;
	}
	return nil;
}

- (id)copyWithZone:(NSZone *)zone {
	return self;
}

- (id)retain {
	return self;
}

- (unsigned)retainCount {
	return UINT_MAX; //denotes an object that cannot be released
}

//- (void)release {
//	//do nothing
//}

- (id)autorelease {
	return self;
}

- (void)dealloc {
   xxxx
	[super dealloc];
}

 

When I try to contruct a new thread to do sth:

 

[NSThread detachNewThreadSelector:@selector(xxx) toTarget:self withObject:nil];

 It will call retain method, and when the thread end it will call dealloc automatically

 

Bcz the we have redefine the retain method, that will cause the problem

 

- (id)retain {
	return self;
}

 So, my solution is remove the retain defination, and normally we will not retain or alloc a singleton object.

 

That's all.

//************************************************************

I met a error of muti-thread today:

reason: '-[__NSCFType isValid]: unrecognized selector sent to instance

I trager a timer and set to a local var, but next time I user the timer will raise upper error, from debug I know the timer is exist and never be release. But the loop function never be called. That make me think out a previous problem, if raise a timer in a thread the timer will not effect. That's the reason. And even cause crash if isValid is called.

你可能感兴趣的:(Singleton)