swift 闭包(类似OC中block)

swift中的闭包

类似OC中block

  • OC中block 回顾
    创建个HttpTool类
    .h
@interface HttpTool : NSObject

// void(返回值)(^代表block)(参数)
- (void)loadData:(void(^)(NSString *jsonData))callBack;

@end

.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]);
            
            //调用block
            callBack(@"json数据");
        });
    });
}

@end

控制器中

#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 *)touches withEvent:(UIEvent *)event
{
//self.tools 调用 loadData:方法 
//loadData:方法中调用block,并传入NSString参数
//下面的jsonData 即为block回调的NSString参数

    [self.tools loadData:^(NSString *jsonData) {
        NSLog(@"在ViewController拿到数据:%@", jsonData);
    }];
}
  • swift中的闭包
  • 闭包的类型
() -> ()
闭包的类型: (参数列表) -> (返回值类型)

创建个HttpTool类

import UIKit

class HttpTool: NSObject {
    // 闭包的类型: (参数列表) -> (返回值类型)
    func loadData(callBack : (jsonData : String) -> ()) {

        dispatch_async(dispatch_get_global_queue(0, 0)) { () -> Void in
            print("发送网络请求:\(NSThread.currentThread())")
            
            dispatch_sync(dispatch_get_main_queue(), { () -> Void in
                print("获取到数据,并且进行回调:\(NSThread.currentThread())")
                
                callBack(jsonData: "jsonData数据")
            })
        }
    }
}

控制器中

import UIKit

class ViewController: UIViewController {
    
//这里的 HttpTool 不需要导入,swift特性
    var tools : HttpTool = HttpTool()
    
    override func touchesBegan(touches: Set, withEvent event: UIEvent?) {

        tools.loadData { (jsonData) -> () in

            print("在ViewController拿到数据:\(jsonData)")
          
        }
    }
}
  • 闭包中的循环引用解决
    还是上面的例子,针对闭包中的使用 self 造成循环引用的解决
override func touchesBegan(touches: Set, withEvent event: UIEvent?) {

        /*
        解决方法一:
        类似oc中 __weak typeof(self) weakself = self 写法
        weakself?.view
        如果前面的可选类型,没有值,后面所有的代码都不会执行
        如果前面的可选类型,有值,系统会自动将weakself进行解包,并且使用weakself
        */
        weak var weakself = self
        tools.loadData { (jsonData) -> () in
            // print("在ViewController拿到数据:\(jsonData)")
            weakself?.view.backgroundColor = UIColor.redColor()
        }

       /*
       解决方法二: 推荐使用该方式
       swift 特有写法,在参数jsonData前面加上 [weak self]
       注意使用也是self? 可选类型,系统自动解包
      */
        tools.loadData {[weak self] (jsonData) -> () in
            // print("在ViewController拿到数据:\(jsonData)")
            self?.view.backgroundColor = UIColor.redColor()
        }
    }
  • swift 中的 dellloc
// deinit相当OC中的dealloc方法,当对象销毁时会调用该函数
    deinit {
        print("ViewController -- deinit")
    }

你可能感兴趣的:(swift 闭包(类似OC中block))