Mixing Blocks and Delegates in Objective-C [duplicate]

≯℡__Kan透↙ 提交于 2020-01-06 14:09:23

问题


Is it possible to run a block when a delegate receives a message?

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.


回答1:


You absolutely can. That is how all completion handlers / callbacks work. In fact, that is what a block is for.

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

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.

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.



来源:https://stackoverflow.com/questions/29806516/mixing-blocks-and-delegates-in-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!