简体   繁体   English

块内阻止= EXC_BAD_ACCESS

[英]Block inside block = EXC_BAD_ACCESS

I have a singleton class the handle all the Game Center logic: 我有一个单例类处理所有Game Center逻辑:

typedef void (^GameCenterCallbackFinishUpdating)();

- (void)getAllMatches:(GameCenterCallbackFinishUpdating)onComplete
{
    [GKTurnBasedMatch loadMatchesWithCompletionHandler:^(NSArray *matches, NSError *error)
    {      
        //Do stuff here... 
        onComplete();
    }];
}

From another viewController I use: 从另一个viewController我使用:

[[GameCenterHelper sharedHelper] getAllMatches:^{

    [self.myTableView reloadData]; 

}];

It works great when I'm in the app, but once I close the app (background) and then start it up again, I get: 当我在应用程序中时,它工作得很好,但是一旦我关闭应用程序(背景)然后再次启动它,我得到:

    onComplete();     ---- Thread 1: EXC_BAD_ACCESS (code=2, address=0xc)

What am I doing wrong here? 我在这做错了什么?

some background info: the blocks are objects and if any block is nil and you try to call them, it crashes the application. 一些背景信息:块是对象,如果任何块是 nil 并且你试图调用它们,它会崩溃应用程序。

somewhere and somehow the block onComplete becomes nil before you call it. 在某个地方以某种方式,在你调用之前,块onComplete变为nil the following if (...) statement helps you to prevent to call a nil pointer, so the application won't crash. 以下if (...)语句可以帮助您防止调用nil指针,因此应用程序不会崩溃。

if (onComplete) onComplete();

Thanks to @holex and @Paul.s for explaining it well. 感谢@holex和@ Paul.s的解释。 I had the similar situation where I was sending block as method parameter( completionHandler ). 我有类似的情况,我发送块作为方法参数( completionHandler )。

- (void)callX:(NSString *)xyz withCompletionHandler:(void (^)(NSString *response))completion
{
    completion(something);
}

And there are two situations either I am using this block like: 有两种情况,我使用这个块像:

[MyClass sharedInstance] callX:@"abc" withCompletionHandler:^(NSString *response) {
    if (response) {
        //do something
    }
}];

or this block could be nil as method parameter: 或者此块可以是nil作为方法参数:

[MyClass sharedInstance] callX:@"abc" withCompletionHandler:nil];

In second case when block was being passed nil as method parameter this caused EXC_BAD_ACCESS on completion() . 在第二种情况下,当块传递nil作为方法参数时,这EXC_BAD_ACCESS完成时导致EXC_BAD_ACCESS () So as @holex states that the blocks are objects and if any block is nil and you try to call them, it crashes the application. 因此@holex声明块是对象,如果任何块是nil并且你试图调用它们,它会崩溃应用程序。 A single if saves lot of my time 单个如果节省了我很多时间

- (void)callX:(NSString *)xyz withCompletionHandler:(void (^)(NSString *response))completion
{
    if (completion)
        completion(something);
}

PS: this explanation only for NERDS like me. PS:这个解释仅适用NERDS像我这样的NERDS | | ' L ' | 'L'|

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

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