我创建了一个 NSObject,唯一的目的是锁定。我的问题是,在我的 dealloc 中,我如何释放(从内存中)锁。我读过你不应该修改同步中的锁对象。但是在我的场景中,我认为从dealloc中的@synchronized完成到调用[_lockObject release]的时间之间,不同线程中的另一个方法可能会获取_lockObject。因此,如果在持有 _lockObject 时调用 [_lockObject release],则可能会发生不好的事情。
在我的 dealloc 方法中处理锁的正确方法是什么?
-(id)initWithImageFileName:(NSString*)imageFileName
{
if (self = [super init])
{
_imageFileName = [imageFileName retain];
_loadBackgroundCalled = NO;
_deallocing = NO;
_lockObject = [[NSObject alloc]init];
}
return self;
}
-(void)dealloc
{
_deallocing = YES;
@synchronized(_lockObject)
{
..... <releases some stuff>
}
[_lockObject release];
_lockObject = nil;
[_imageFileName release];
_imageFileName = nil;
[super dealloc];
}
-(void)loadBackground
{
@synchronized(_lockObject)
{
if (!_deallocing)
{
if (!_loadBackgroundCalled)
{
_loadBackgroundCalled = YES;
....
}
}
}
}
-(void)loadSprite:(XYTexture*)texture
{
@synchronized(_lockObject)
{
....
}
}
-(void)unloadBackground
{
@synchronized(_lockObject)
{
if (!_deallocing)
{
.....
_loadBackgroundCalled = NO;
}
}
}