问题
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