Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question

2 Answers 2

up vote 2 down vote accepted
//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
    }];
share|improve this answer
    
This will successfully block control from moving ahead –  amar Dec 1 '12 at 8:17
    
I have passed string you can pass any thing –  amar Dec 1 '12 at 8:20

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);
        }
    });
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.