0

プロパティが nil でない場合に操作を実行するタイマーがありますが、nil をチェックしてから操作を実行するまでの間に、イベントによってプロパティが nil に設定されます。実際には、プロパティを nil に設定できるイベントがいくつかあります。同じボートにあるタイマーがチェックしている他のプロパティもあります。

これを解決する最もエレガントでスケーラブルな方法は何ですか?

  1. プロパティのすべての使用を同期ブロックでラップしますか?
  2. タイマーの開始時にロックを設定/解放し、各イベントでロックの待機を確認しますか?
  3. 他の何か?
4

2 に答える 2

1

正確な状況はよくわかりませんが、プロパティにカスタムセッターを作成して、タイマーがnilに設定されているときにタイマーをキャンセルすることを検討してください。

于 2012-06-13T15:11:54.970 に答える
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;
于 2012-06-13T16:16:08.177 に答える