Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Callback vs CompletionHandler #1

Closed
roveretoa opened this issue Jan 18, 2017 · 1 comment
Closed

Callback vs CompletionHandler #1

roveretoa opened this issue Jan 18, 2017 · 1 comment
Labels

Comments

@roveretoa
Copy link

roveretoa commented Jan 18, 2017

cool... 《有一种 Block 叫 Callback,有一种 Callback 做 CompletionHandler》被文章名字深深吸引了,博主思考深刻,提出的观点有利于更简单的理解事物逻辑。

“不是所有 Block 都可以叫做 CompletionHandler” 我觉得用 Block 实现的“ CompletionHandler/callback”是同一个消息传递的正法两面,在 “ CompletionHandler + Delegate”组合中,Delegate方法实现的地方 Block 是一个“ CompletionHandler”, 但在Delegate方法使用的地方Block 叫做“ Callback”。这么讲的话,这两处只有一个本质区别: 一处是Block的执行另外一处是Block填充。

对于 Fetch 的这种应用场景,我认为用方法的返回值可以部分替代(与 CompletionHandler 相比无法自由切换线程是个弊端)

NSURLSession 的一个简单函数将 “callback” 命名为了 “completionHandler”:

- (NSURLSessionDataTask *)dataTaskWithURL:(NSURL *)url completionHandler:(void (^)(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error))completionHandler;

另外文中"URLSession:didReceiveChallenge:completionHandler" 的例子,让我想到另外一个也非常普遍的例子(Delegate 方式使用URLSession 时候必不可少的 4个代理函数之一 )

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
                                didReceiveResponse:(NSURLResponse *)response
                                 completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler;

//在代理方法实现代码里面,若是不执行 completionHandler(NSURLSessionResponseAllow) 话,http请求就终止了。

拙见...

@ChenYilong
Copy link
Owner

ChenYilong commented Jan 20, 2017

这两处只有一个本质区别: 一处是Block的执行另外一处是Block填充

这个理解很赞,关于

NSURLSession 的一个简单函数将 “callback” 命名为了 “completionHandler”:

因为 Callback vs CompletionHandler 命名与功能的差别,是我个人的理解,Apple也没有明确的编码规范指出过,只不过如果按照“执行与填充”的功能划分的话,我觉得callback与completionHandler的命名可以区分开来对待。同时也方便调用者理解block的功能。Apple并不遵循这一规则。但总体来说,Block填充这个功能一般都会命名为 “completionHandler”,Block的执行这个功能大多命名为了“callback” ,少部分命名为了 “completionHandler”。

基于你的理解,我对文章做了一些修改,添加了你的见解。741063c

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants