有没有一种好方法可以防止Objective-C中特定位代码的递归?

时间:2021-01-31 22:46:54

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.

这是循环滚动视图的setContentOffset。因此,用户可以在滚动时运行代码。如果您设置了其中两个,并且希望它们相互跟踪,那么对于您提供一个设置另一个的块,您可以获得一个递归的情况,它们会一直相互呼叫。

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?

无论如何,问题是在这种情况下防止递归。鉴于这是一个UI方法,因此只调用主线程,当你从块中调用一个合理的线程时,我的方法是捕获一个简单的标志吗?

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?

是否有任何语言功能或框架模式(在iOS中可用) - 类似于@synchronized或dispatch_once但是为了防止特定代码段的递归?

1 个解决方案

#1


3  

I wouldn't use a static BOOL as a static is implemented at class level. What if you had two instances of this class? They would be shooting each other in the foot! At the very least, use an instance variable (i.e. a property, and don't declare it nonatomic either, just in case).

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

#1


3  

I wouldn't use a static BOOL as a static is implemented at class level. What if you had two instances of this class? They would be shooting each other in the foot! At the very least, use an instance variable (i.e. a property, and don't declare it nonatomic either, just in case).

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