6

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?

Richard J. Ross III
  • 55,009
  • 24
  • 135
  • 201
Matrosov Oleksandr
  • 25,505
  • 44
  • 151
  • 277

4 Answers4

15

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

Julien
  • 963
  • 5
  • 8
  • I try to call block(); and get error Called object '*(struct objc_object **)((char *)self + OBJC_IVAR_$_SettingsHelp.block)' is not a function – Matrosov Oleksandr Feb 28 '12 at 15:18
  • that is because you are declaring it as id. Take a look at [this question](http://stackoverflow.com/questions/3935574/can-i-use-objective-c-blocks-as-properties) to see how you can declare it properly. – murat Feb 28 '12 at 15:28
  • How to do same stuff with swift? i mean if i have a closure and i want just call func doneAction() { self.onActionSheetDone() } – Zaporozhchenko Oleksandr Feb 09 '17 at 02:07
9

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

@property (nonatomic, copy)   id block;
murat
  • 4,893
  • 4
  • 31
  • 29
1

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.

Art Gillespie
  • 8,747
  • 1
  • 37
  • 34
0

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