2012-12-01 76 views
0

從私有庫中,我使用了這樣的塊函數,但不知道它們是如何實際創建的。他們將如何返回到我的班級並執行該塊?Objective-c:創建塊函數

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]; 

這裏,值得注意的一點是,一個test功能可以好好時間(以分鐘爲單位)來完成它的執行,但它完美地打印線塊!即使我的函數已經被執行了。

回答

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>); 
    } 
} 

化妝對象的CALSS,並使用你不需要睡它不會讓控制通至該塊被執行

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

    } 
       errorCallback:(void (^)(NSString *errorMsg)) errorCallback{ 
//get your error value 
    }]; 
+0

這將成功阻止控制前進 – amar

+0

我已經傳遞了字符串,你可以傳遞任何東西 – amar

0

如果你想知道如何該函數內部實現的,它可能是這樣的:

- (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); 
     } 
    }); 
}