2

I have got two UIViewController:

  • MainVC
  • PickerVC

In main view controller I have IBAction method: - showPickerView

In this method I need to create block that will present PickerVC view and wait me while I choose something value on PickerVC view and press Done button.

In this block I need to implement callback that will invoke method in MainVC after I press on button Done.

So, I have used block before, but I don't know how to implement it by myself.

I think first part will be look like this:

- (IBAction)showPickerView {
   __block PickerVC *pickerVC = [[PickerVC alloc] init];
   [pickerVC setFinishBlock:^{
      // Do something after user press on Done button
   }];
   [pickerVC setFailedBlock:^{
      // Do something if something wrong (but this method optional)
   }];
   [pickerVC showPicker];
}
2
  • This page has all the info that you need. Commented Jul 26, 2012 at 9:43
  • if you need a callback why don't you try to create a protocol and use the delegate scheme? or why don't you use the NSNotificationCenter...? Commented Jul 26, 2012 at 10:50

1 Answer 1

7

Add in the header of PickerVC two typedefs

typedef void (^FinishBlock)();
typedef void (^FailedBlock)();

and your declaration of setFinishedBlock takes the FinishBlock

- (void)setFinishBlock:(FinishBlock)finishBlock;
- (void)setFailedBlock:(FailedBlock)failedBlock;

Make an iVar for each block

@interface PickerVC : UIViewController
{
  FinishBlock _finishBlock;
  FailedBlock _failedBlock;
}

In your definition of setFinishedBlock: and setFailedBlock: set the parameter to the iVars

As soon as PickerVC fails or finishes call _failedBlock or _finishedBlock.

The __block statement is used for variables to stay in memory if they are used in a block. So you don't need it in the above code

Sign up to request clarification or add additional context in comments.

2 Comments

like a c function _failedBlock();
Make sure to check for nil first: if (_failedBlock) _failedBlock();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.