Closure Closure Package Introduction
- Closures are very similar to block in OC
- Block in OC is an anonymous function
- Closures in Swift are a special function
- Block and closures are often used for callbacks
- Note: Closures and blocks, the first use may not be used to its syntax, you can follow the use of a simple closure, with the depth of learning, slowly grasp its flexible use of methods.
A review of the usage of block in closures
- Classes that define network requests
@interface httptool: nsobject-(void) Loadrequest: (void (^) ()) Callbackblock; @end @implementation httptool-(void) Loadrequest: (void (^) ()) callbackblock{dispatch_async (Dispatch_get_global_queue (0 , 0), ^{nslog (@ "Load network data:%@", [ Span class= "hljs-built_in" >nsthread CurrentThread]); dispatch_async (Dispatch_get_main_queue (), ^{Callbackblock ();});}); @end
- Make network requests, request to data and use block for callback
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{ [self.httpTool loadRequest:^{ NSLog(@"主线程中,将数据回调.%@", [NSThread currentThread]);
self.view.backgroundColor = [UIColor redColor]; }];}
block的写法: 类型: 返回值(^block的名称)(block的参数) 值: ^(参数列表) { // 执行的代码 };
Note: In the block in the OC above, set in block statement blocksself.view.backgroundColor = [UIColor redColor];不会产生循环引用,原因是,:
控制器中属性定义HttpTool,则控制器会对HttpTool有一个强引用,在block语句块中会对外部引用的变量产生一个强引用,所以block对控制器有一个强引用,但HttpTool不会对block产生一个强引用,所以没有形成闭环,不会产生循环引用。若是解决循环引用可以用:__weak typeof(self) weakSelf = self;typeof(self)意思是取self的类型,所以也可以:__weak vc *weakSelf = self。
Swift Learning Day 15th: Closures