2012-06-13 20 views
0

我有一個定時器,如果屬性不是零,但是在檢查零和執行操作之間執行操作,則事件將屬性設置爲零。實際上有幾個事件都可以將財產設置爲零。還有其他屬性,定時器正在檢查是在同一條船上。iOS:在定時器檢查屬性是否爲零後,事件將propert設置爲零

什麼是最優雅和可擴展的解決方法?

  1. 將該屬性的每次使用都包裝在同步塊中?
  2. 在計時器的開始處設置/釋放鎖定並檢查是否在每個事件中等待鎖定?
  3. 還有別的嗎?

回答

1

我不太確定你的確切情況,但是你可能想考慮寫一個自定義setter來取消定時器的屬性,當它被設置爲nil時?

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;