Swift Learning Day 15th: Closures

Source: Internet
Author: User

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 notation Summary:
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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.