我有一个计时器,如果它不是nil就对属性执行操作,但在检查nil和执行操作之间,事件将属性设置为nil。实际上有几个事件都可以将属性设置为nil。计时器正在检查的其他属性也在同一条船上。
解决此问题的最优雅,最具扩展性的方法是什么?
答案 0 :(得分:1)
我对你的确切情况不太确定,但你可能想考虑在属性中编写一个自定义setter,当它设置为nil时会取消定时器吗?
答案 1 :(得分:0)
我选择了Paul de Lange的答案,因为它对我来说很有意义。我不想找到我设置属性的每个地方并将其包装在@synchronized
块中。
对于其他需要做类似事情的人来说,这是我提出的代码:
@interface MyClass {
//...
//The iVar, note that the iVar has a different name than the property, see the @synthesize command
RefreshOperation *_refreshOperation;
//...
}
@property (nonatomic, retain) RefreshOperation *refreshOperation;
@implementation MyClass
//...
//The timer's callback
- (void)statusTimerEvent:(NSTimer *)aTimer
{
//Block/wait for thread safe setters/getters
@synchronized(self)
{
if (self.refreshOperation)
{
self.status = [self.refreshOperation status];
progressView.progress = self.refreshOperation.progress;
}
}
}
//...
//Thread safe setter for the refreshOperation property
- (void)setRefreshOperation:(RefreshOperation *)refreshOperation:(RefreshOperation *)newRefreshOperation
{
@synchronized(self)
{
if (_refreshOperation != newRefreshOperation)
{
[_refreshOperation release];
_refreshOperation = [newRefreshOperation retain];
}
}
}
//Thread safe getter for the refreshOperation property
- (RefreshOperation *)refreshOperation
{
id result = nil;
@synchronized(self)
{
result = [_refreshOperation retain];
}
return [result autorelease];
}
//...
- (void)dealloc
{
//...
self.refreshOperation = nil;
[super dealloc];
}
//...
//Connect the property |refreshOperation| to the iVar |_refreshOperation|; having the same name for both results in warning about the local variable hiding a property
@synthesize refreshOperation = _refreshOperation;