iOS:在计时器检查属性是否为nil之后,事件将属性设置为nil

时间:2012-06-13 15:07:15

标签: objective-c ios events timer

我有一个计时器,如果它不是nil就对属性执行操作,但在检查nil和执行操作之间,事件将属性设置为nil。实际上有几个事件都可以将属性设置为nil。计时器正在检查的其他属性也在同一条船上。

解决此问题的最优雅,最具扩展性的方法是什么?

  1. 在同步块中包装该属性的每次使用吗?
  2. 在计时器开头设置/解除锁定并检查每次事件中是否锁定?
  3. 别的什么?

2 个答案:

答案 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;