0

Here is what I'm currently doing for a looping scroll-view:

// Call the on-scroll block
static BOOL inOnScrollBlock = NO;
if((_onScrollBlock != nil) && !inOnScrollBlock)
{
    inOnScrollBlock = YES;
    _onScrollBlock(self, self.loopOffset);
    inOnScrollBlock = NO;
}

This is in the setContentOffset for the looping scroll view. So the user can run code whenever it scrolls. If you set up two of these and you want them to track each other, so for both you supply a block that sets the other then you can get a recursive situation where they keep calling each other.

Actually in this case it's not too bad as there's a separate check to see if the value being set is already set before doing all the more advanced stuff, but because it's a looping view there are multiple equivalent values so it can happen a few times.

Anyway, the question is about preventing recursion in this kind of situation. Given that this is a UI method and therefore only called on the main thread, is my approach of a simple flag to catch when you're being called from within the block a reasonable one, or not?

Are there any language features or framework patterns (available in iOS) to do this - similar to @synchronized or dispatch_once but to prevent recursion of a particular code section?

4

1 回答 1

3

我不会使用静态 BOOL,因为静态是在类级别实现的。如果你有这个类的两个实例怎么办?他们会在脚下互相射击!至少,使用实例变量(即属性,也不要声明它nonatomic,以防万一)。

于 2013-05-01T23:47:05.847 回答