Invoke block iOS

血红的双手。 提交于 2019-11-30 15:49:02

问题


I try to invoke some block, but I run into a EXC_BAD_ACCESS.

-(void) methodA {
   self.block = ^ {
       [self methodB];
   };
}

-(void) webViewDidFinishLoad:(UIWebView *)webView {
       [block invoke]; // error here (block is not valid id type).
}

-(void)methodB {
    //do something
}

Any thoughts on why this is happening?


回答1:


You should use copy attribute when you are declaring block property. Like:

@property (nonatomic, copy)   id block;



回答2:


if you want to invoke the block you can simply do this block(); instead of [block invoke];

for more details, see the Block Programming Topics




回答3:


You have to put the block on the heap:

self.block = Block_copy(^{
    [self someMethod];
});

EDIT: @murat's answer is correct, too (and probably better). One way or the other, you have to copy the block, since blocks are actually created on the stack and not on the heap.

For more on blocks you want to keep around, see "Copying Blocks" and "Patterns to Avoid" in the documentation.




回答4:


you can declare a property for block in .h file like this and it will not give bad-excess -

    typedef int (^devideEquallyBlock)(int);
    @property (nonatomic, copy) devideEquallyBlock callbackBlock;

Make sure that you declare copy not retain for more details how to declare properties blocks programming in ios/objective-c



来源:https://stackoverflow.com/questions/9484123/invoke-block-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!