博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
block作为函数参数回调
阅读量:6554 次
发布时间:2019-06-24

本文共 2229 字,大约阅读时间需要 7 分钟。

Blocks make this much easier, however, because you can define the callback behavior at the time you initiate the task, like this:

- (IBAction)fetchRemoteInformation:(id)sender {
    [self showProgressIndicator];
 
    XYZWebTask *task = ...
 
    [task beginTaskWithCallbackBlock:^{
        [self hideProgressIndicator];
    }];
}
This example calls a method to display the progress indicator, then creates the task and tells it to start. The callback block specifies the code to be executed once the task completes; in this case, it simply calls a method to hide the progress indicator. Note that this callback block captures self in order to be able to call the hideProgressIndicator method when invoked. It’s important to take care when capturing self because it’s easy to create a strong reference cycle, as described later in Avoid Strong Reference Cycles when Capturing self.
In terms of code readability, the block makes it easy to see in one place exactly what will happen before and after the task completes, avoiding the need to trace through delegate methods to find out what’s going to happen.
The declaration for the beginTaskWithCallbackBlock: method shown in this example would look like this:
- (void)beginTaskWithCallbackBlock:(void (^)(void))callbackBlock;
The (void (^)(void)) specifies that the parameter is a block that doesn’t take any arguments or return any values. The implementation of the method can invoke the block in the usual way:
- (void)beginTaskWithCallbackBlock:(void (^)(void))callbackBlock {
    ...
    callbackBlock();
}
Method parameters that expect a block with one or more arguments are specified in the same way as with a block variable:
- (void)doSomethingWithBlock:(void (^)(double, double))block {
    ...
    block(21.0, 2.0);
}
A Block Should Always Be the Last Argument to a Method
It’s best practice to use only one block argument to a method. If the method also needs other non-block arguments, the block should come last:
- (void)beginTaskWithName:(NSString *)name completion:(void(^)(void))callback;
This makes the method call easier to read when specifying the block inline, like this:
    [self beginTaskWithName:@"MyTask" completion:^{
        NSLog(@"The task is complete");
    }];

转载于:https://www.cnblogs.com/NSNULL/p/4482350.html

你可能感兴趣的文章
HTTP深入浅出 http请求
查看>>
为YUM设置代理的方法
查看>>
Java 编程的动态性 第1 部分: 类和类装入--转载
查看>>
再谈ABC
查看>>
【转】持久化消息队列之MEMCACHEQ
查看>>
java-Mail
查看>>
Dom4j学习笔记
查看>>
C语言 HTTP上传文件-利用libcurl库上传文件
查看>>
[MEAN Stack] First API -- 7. Using Route Files to Structure Server Side API
查看>>
调试逆向分为动态分析技术和静态分析技术(转)
查看>>
Android webview使用详解
查看>>
业务对象和BAPI
查看>>
程序源系统与当前系统不一致:Carry out repairs in non-original systems only if urgent
查看>>
微软职位内部推荐-Senior Software Engineer
查看>>
程序中的魔鬼数字
查看>>
SVN高速新手教程
查看>>
session cookie
查看>>
如何在Vblock里配置Boot from SAN
查看>>
ZBar之ZBarReaderViewController
查看>>
Nuget~管理自己的包包~丢了的包包快速恢复
查看>>