简体   繁体   中英

iOS completion block not returning control

I have written a lot of completion blocks but not sure why this is happening. The control of a block based function should not go forward if we call the block with the appropriate argument. But in my case it is doing so.

- (void) validateFormWithCompletion: (void(^)(BOOL valid)) completion
{
    if (! [NetworkConstant appIsConnected])
    {
        [[AppThemeManager sharedInstance] showNoInternetMessage];

        completion(NO);
    }

    emailIdTF.text = [emailIdTF.text trimWhiteSpaceAndNextLine];

    if (emailIdTF.text.length == 0)
    {
        [[AppThemeManager sharedInstance] showNotificationWithTitle:@"Incomplete" subtitle:@"Please fill in a valid email id" duration:durationForTSMessage withTypeOfNotification:notificationWarning];

        completion(NO);
    }

    else
    {
        completion(YES);
    }
}

If there is no internet connection, the control should return from the first occurrence of completion(NO);. But instead it moves forward to email length check. Am I doing something wrong here?

If I understand your question, you need to add a return .

if (! [NetworkConstant appIsConnected])
{
    [[AppThemeManager sharedInstance] showNoInternetMessage];

    completion(NO);

    return;
}

The return prevents the rest of the method from being executed if there is no network connection.

It also seems like there is no reason to be using a completion handler. There is no asynchronous processing inside your method.

Most probably the other times you called completion blocks they were placed within other completion blocks, called by asynchronous tasks, which is not the case in the given example. Thus using an completion block does not make sense how I understand your example.

- (BOOL) validateFormWithCompletion:(void(^)(BOOL valid)) completion
{
    if (! [NetworkConstant appIsConnected]) {
        [[AppThemeManager sharedInstance] showNoInternetMessage];

        return NO;
    }

    emailIdTF.text = [emailIdTF.text trimWhiteSpaceAndNextLine];

    if (emailIdTF.text.length == 0) {
        [[AppThemeManager sharedInstance] showNotificationWithTitle:@"Incomplete" subtitle:@"Please fill in a valid email id" duration:durationForTSMessage withTypeOfNotification:notificationWarning];

        return NO;
    } else {
        return YES;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM