Objective-C中的混合块和代表 [英] Mixing Blocks and Delegates in Objective-C
问题描述
当委托人收到消息时是否可以运行一个块?
Is it possible to run a block when a delegate receives a message?
例如,如果我有一个框架,该框架以void块作为参数(我们将其称为成功"块),并且在接收到以下消息时正在使用NSURLConnection委托来处理那些方法参数:来自网页的响应,如何调用方法参数中传递的成功"块?
For example, if I had a framework that took a void block as a parameter (we'll call it the "success" block), and was using an NSURLConnection delegate to do stuff with those method arguments, when I receive a response from the webpage, how can I call the "success" block passed in the method parameters?
这对我来说很难做到,而且我显然没有任何代码,但是我可以澄清您是否有任何疑问.
This is really hard for me to explain, and I obviously don't have any code for this, but I can clarify if you have any questions.
推荐答案
您绝对可以.这就是所有完成处理程序/回调的工作方式.实际上,这就是 的一个块.
You absolutely can. That is how all completion handlers / callbacks work. In fact, that is what a block is for.
举一个简单的例子,考虑以下NSURLConnection类方法:
To take a simple example, consider this NSURLConnection class method:
+ (void)sendAsynchronousRequest:(NSURLRequest *)request
queue:(NSOperationQueue *)queue
completionHandler:(void (^)(NSURLResponse *response,
NSData *data,
NSError *connectionError))handler
对于第三个参数,您传递了一个块.当请求结束后,在将来的某个时间,NSURLConnection会做什么?它会调用该块.
For the third parameter, you pass a block. And when the request is all over, some time in the future, what does NSURLConnection do? It calls the block.
因此,您可以执行与NSURLConnection完全相同的操作.您可以编写一个占用一个块的方法,按住该块,执行可能要花费一些时间的操作,然后稍后调用该块.
So, you can do exactly the same that NSURLConnection is doing. You can write a method that takes a block, you hold on to the block, you do something that perhaps takes some time, and then later you call the block.
这篇关于Objective-C中的混合块和代表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!