简体   繁体   English

未调用完成块。 如何检查有效性?

[英]Completion block not being called. How to check validity?

I have this method which takes a block, but that block isn't always called. 我有这种方法需要一个块,但并不总是调用该块。 See the method: 见方法:

- (void)updateWithCompletion:(void (^)(void))completion {
    [MYObject myMethodWithCompletion:^(NSArray *array, NSError *error) {
        if (error) {
            NSLog(@"%s, ERROR not nil", __FUNCTION__);
            completion();
            return;
        }

        NSLog(@"%s, calling completion %d", __FUNCTION__, &completion);
        completion();
        NSLog(@"%s, finished completion", __FUNCTION__);
    }];
}

I have some more NSLogs inside completion. 我在完成过程中还有一些NSLogs。 Sometimes this program counter just blows right past the call to completion() in the code above. 有时,此程序计数器刚好在上面的代码中对completion()的调用之后结束。 I don't see why this would be as the calling code always passes a literal block of code as input. 我不明白为什么会这样,因为调用代码总是将原义的代码块作为输入传递。

If you're curious of the output of the line containing the addressof operator, it's always something different, but never 0 or nil. 如果您对包含addressof运算符的行的输出感到好奇,它总是有所不同,但绝不会为0或nil。

What would cause completion not to be executed? 是什么导致无法执行完成?

It turns out that completion was pointing to a different code block than I was expecting. 事实证明,完成指向的代码块与我期望的不同。 updateWithCompletion was called from viewWillAppear with an empty code block. 从viewWillAppear调用了updateWithCompletion,其中包含一个空代码块。 This is why I wasn't seeing the NSLog statements. 这就是为什么我没有看到NSLog语句的原因。 Once I saw that I had an empty code block it was obvious how to fix the problem. 看到我有一个空的代码块后,很明显如何解决问题。

Lessons learned: If a code block is nil, the program will crash. 获得的经验:如果代码块为nil,程序将崩溃。 This wasn't happening, so that meant that it was calling something other than what I was expecting. 这没有发生,所以这意味着它正在调用我所期望的以外的东西。

Hope this helps someone. 希望这对某人有帮助。

What do you mean, the program counter blows past the block? 您是什么意思,程序计数器越过了程序段? Completion blocks are nearly always executed asynchronously. 完成块几乎总是异步执行的。 This means that, yes, the program counter will jump from just before the call to -myMethodWithCompletion: directly to the end of the method where it returns back to the caller. 这意味着,是的,程序计数器将从调用-myMethodWithCompletion:之前的-myMethodWithCompletion:直接跳转到方法的末尾,并在此返回给调用方。 And then at some point in the future, the completion block will be called. 然后在将来的某个时刻,将调用完成模块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM