Block最常见的就是网络请求中,我们先写一个网络请求的类
HttpTool.h
#import <Foundation/Foundation.h>
@interface HttpTool : NSObject
-(void)loadData:(void(^)(NSString *jsonData))callBack;
@end
HttpTool.m
#import "HttpTool.h"
@implementation HttpTool
-(void)loadData:(void(^)(NSString *))callBack
{
// 异步发送请求
dispatch_async(dispatch_get_global_queue(0, 0), ^{
NSLog(@"发送网络请求:%@", [NSThread currentThread]);
// 回到主队列
dispatch_sync(dispatch_get_main_queue(), ^{
NSLog(@"拿到数据进行回调:%@", [NSThread currentThread]);
// 执行回调函数
callBack(@"json数据");
});
});
}
@end
然后在控制器测试:
// ViewController.m
#import "ViewController.h"
#import "HttpTool.h"
@interface ViewController ()
@property(nonatomic,strong)HttpTool *tools;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.tools = [[HttpTool alloc] init];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
[self.tools loadData:^(NSString *jsonData) {
NSLog(@"在ViewController拿到数据:%@",jsonData);
}];
}
@end
number = 2 说明发送网络请求确实是在子线程。
思考
基于以上代码,我们在回调方法里设置view的背景颜色,是否会造成循环引用?
[self.tools loadData:^(NSString *jsonData) {
// NSLog(@"在ViewController拿到数据:%@",jsonData);
self.view.backgroundColor = [UIColor redColor];
}];
查看控制移除的时候是否会调用dealloc方法
- (void)dealloc
{
NSLog(@"ViewController控制销毁了");
}
为了便于测试,我们需要装进导航控制器里,但返回的时候,查看dealloc是否打印?
当从ViewController返回时,我们发现它的dealloc 方法被调用了
ViewController控制销毁了 这句是在点击了”Back按钮”之后才打印的。
以上实验说明:当前是没有循环引用的,那么什么情况下才会有循环引用呢?
让HttpTool 对象和 Block 直接强引用就可以
// HttpTool.m
#import "HttpTool.h"
@interface HttpTool()
/**
* 用来保存回调方法
*/
@property(nonatomic,copy) void(^callBack)(NSString *name);
@end
@implementation HttpTool
-(void)loadData:(void(^)(NSString *))callBack
{
// 先保存回调方法
self.callBack = callBack;
// 异步发送请求
dispatch_async(dispatch_get_global_queue(0, 0), ^{
NSLog(@"发送网络请求:%@", [NSThread currentThread]);
// 回到主队列
dispatch_sync(dispatch_get_main_queue(), ^{
NSLog(@"拿到数据进行回调:%@", [NSThread currentThread]);
// 执行回调函数
callBack(@"json数据");
});
});
}
@end
那么我们以往是怎么解决这种循环引用问题的呢?
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
__weak ViewController *weakSelf = self;
[self.tools loadData:^(NSString *jsonData) {
// NSLog(@"在ViewController拿到数据:%@",jsonData);
weakSelf.view.backgroundColor = [UIColor redColor];
}];
}

本文探讨了Block在iOS开发中的使用,特别是在网络请求类中的应用场景。通过一个简单的例子,分析了如何避免Block导致的循环引用问题,并提出了有效的解决方案。
8万+

被折叠的 条评论
为什么被折叠?



