0

From a private library, I'm using a block function like this, but don't know how actually they are created. How they will returned back to my class and execute the block ?

ImAnotherClass *sameObj = [[ImAnotherClass alloc] init];

[sameObj testFunctionWithBlock:^(BOOL success, NSError *error) 
{
    if(!error)
    NSLog(@"you'll only read this, once test function was done!");
}];

[sameObj release];

Here, the notable thing is, a testfunction can take good time (in minutes) to complete its execution, but it will perfectly print the line in block ! even my function gets executed already.

2 Answers 2

4
//your class .h
 + (void) doSomething:(NSString *) string
                   successCallback:(void (^)(id successValue)) successCallback
         errorCallback:(void (^)( NSString *errorMsg)) errorCallback;


//your class.m
+ (void) doSomething:(NSString *) string
                   successCallback:(void (^)(id successValue)) successCallback
         errorCallback:(void (^)( NSString *errorMsg)) errorCallback {

   //do your work here
   //set your bool for error

    if(error) {
        errorCallback(<error value>);
    } else {


        successCallback(<value on success>);
    }
}

make object of your calss and use you dont need sleep it will not let control pass till the block is executed

 [objYourClass  doSomething:(NSString *) string
                           successCallback:(void (^)(id successValue)) successCallback{
    //get your success value

    }
                 errorCallback:(void (^)( NSString *errorMsg)) errorCallback{
//get your error value
    }];
Sign up to request clarification or add additional context in comments.

2 Comments

This will successfully block control from moving ahead
I have passed string you can pass any thing
0

If you’re wondering how the function is implemented inside, it could look like this:

- (void) doSomethingWithCompletion: (dispatch_block_t) completion
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        sleep(10); // wait for ten seconds
        if (completion) {
            dispatch_async(dispatch_get_main_queue(), completion);
        }
    });
}

Comments

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.