Question

I have been reading up on Objectice-C blocks as I have been running into them more and more lately. I have been able to solve most of my asynchronous block execution problems, however I have found one that I cannot seem to fix. I thought about making an __block BOOL for what to return, but I know that the return statement at the end of the method will be executed before the block is finished running. I also know that I cannot return a value inside the block.

- (BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(id)sender {

    if ([identifier isEqualToString:@"Reminder Segue"]) {

        eventStore = [[EKEventStore alloc] init];

        [eventStore requestAccessToEntityType:EKEntityTypeReminder completion:^(BOOL granted, NSError *error) {

            if (!granted) {

                UIAlertView *remindersNotEnabledAlert;
                remindersNotEnabledAlert = [[UIAlertView alloc] initWithTitle:@"Reminders Not Enabled" message:@"In order for the watering reminder feature to function, please allow reminders for the app under the Privacy menu in the Settings app." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];

            //I would like to put a simple return NO statement here, but I know it is impossible
            }
        }];
    }

    return YES;
}

How do I create a simple return statement from a block?

Was it helpful?

Solution

While the immediate idea might be to make your asynchronous request synchronous, that's rarely a good idea, and do to so in the middle of a segue, such as this case, is likely to be problematic. It's almost never a good idea to try to make an asynchronous method synchronous.

And, as smyrgl points out, the idea of "can't I just return a value from the block" is intuitively attractive, but while you can define your own blocks that return values (as Duncan points out), you cannot change the behavior of requestAccessToEntityType such that it returns a value in that manner. It's inherent in its asynchronous pattern that you have to act upon the grant state within the block, not after the block.

So, instead, I would suggest a refactoring of this code. I would suggest that you remove the segue (which is likely being initiated from a control in the "from" scene) and not try to rely upon shouldPerformSegueWithIdentifier to determine whether the segue can be performed as a result of a call to this asynchronous method.

Instead, I would completely remove that existing segue and replace it with an IBAction method that programmatically initiates a segue based upon the result of requestAccessToEntityType. Thus:

  • Remove the segue from the button (or whatever) to the next scene and remove this shouldPerformSegueWithIdentifier method;

  • Create a new segue between the view controllers themselves (not from any control in the "from" scene, but rather between the view controllers themselves) and give this segue a storyboard ID (for example, see the screen snapshots here or here);

  • Connect the control to an IBAction method, in which you perform this requestAccessToEntityType, and if granted, you will then perform this segue, otherwise present the appropriate warning.

    Thus, it might look something like:

    - (IBAction)didTouchUpInsideButton:(id)sender
    {
        eventStore = [[EKEventStore alloc] init];
    
        [eventStore requestAccessToEntityType:EKEntityTypeReminder completion:^(BOOL granted, NSError *error) {
    
            // by the way, this completion block is not run on the main queue, so
            // given that you want to do UI interaction, make sure to dispatch it
            // to the main queue
    
            dispatch_async(dispatch_get_main_queue(), ^{
                if (granted) {
                    [self performSegueWithIdentifier:kSegueToNextScreenIdentifier sender:self];
                } else {
                    UIAlertView *remindersNotEnabledAlert;
                    remindersNotEnabledAlert = [[UIAlertView alloc] initWithTitle:@"Reminders Not Enabled" message:@"In order for the watering reminder feature to function, please allow reminders for the app under the Privacy menu in the Settings app." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
                    [remindersNotEnabledAlert show];
                }
            });
        }];
    }
    

OTHER TIPS

You CAN return a value from a block, just like from any function or method. However, returning a value from a completion block on an async method does not make sense. That's because the block doesn't get called until after the method finishes running at some later date, and by then, there is no place to return a result. The completion method gets called asynchronously.

In order to make a block return a value you need to define the block as a type that does return a value, just like you have to define a method that returns a value.

Blocks are a bit odd in that the return value is assumed to be void if it's not specified.

An example of a block that returns a value is the block used in the NSArray method indexOfObjectPassingTest. The signature of that block looks like this:

(BOOL (^)(id obj, NSUInteger idx, BOOL *stop))predicate

The block returns a BOOL. It takes an object, an integer, and a pointer to a BOOL as parameters. When you write a block of code using this method, your code gets called repeatedly for each object in the array, and when you find the object that matches whatever test you are doing, you return TRUE.

If you really want to make a block synchronous (although I question the validity of doing so) your best bet is to use a dispatch_semaphore. You can do it like this:

dispatch_semaphore_t mySemaphore = dispatch_semaphore_create(0);

__block BOOL success;

        [eventStore requestAccessToEntityType:EKEntityTypeReminder completion:^(BOOL granted, NSError *error) {
             success = granted;
             dispatch_semaphore_signal(mySemaphore);
        }];

dispatch_semaphore_wait(mySemaphore, DISPATCH_TIME_FOREVER);

However again I don't think you want to do this, especially in a segue as it will stall the UI. Your better bet is to rearchitect what you are doing so that you don't have a dependency on the async process being completed in order to continue.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top