jeremy gv jeremy gv - 5 months ago 43
Objective-C Question

Pass Data back by using blocks instead of delegate

I have been trying to pass data using blocks

sent data backward

declare block in your secondViewController .h file

@property (nonatomic, copy)void(^myBlock)(NSString *);

call block wherever you need to pass data from .m file of secondViewController

myBlock(@"this will displayed in firstViewController");

3.import above .h file in your firstViewController .m file and define your block as

secondViewController *ref =[[secondViewController alloc ]init];
ref.myBlock =^void(NSString *data)

while run time I am getting EXC bad Access Error Can anyone sort the issue to this?


Here [[secondViewController alloc ]init]; you are creating a new instance of the view controller so you can set the block on it, but then it isn't used and gets destroyed. You need to use prepareForSegue or similar depending on how you display the VC so you set the block on the correct instance.

VC2 should generally check if the block is nil before calling it too.

The property should also be strong, not copy. ARC does the right thing anyway.