OC以及Swift中的闭包

2018/9/5 posted in  iOS

因为在实际开发中闭包会经常用到,几乎和代理实现同样的功能,所以我们来探究一下OC和 swift中的闭包。

Objecticve-C

①声明Block

OC中有两种声明方式

  1. 方式一

    typedef void(^BlockName)(NSString * name);
    @property(nonatomic,copy)BlockName hello;
    
  2. 方式一

    @property(nonatomic,copy)void(^Test)(NSString * name);
    

②实现Block

self.Test = ^(NSString *name) {
        NSLog(@"%@",name);
    };

self.hello = ^(NSString *name) {
        NSLog(@"%@",name);
    };

③调用Block

self.Test(@"hello");
self.hello(@"hello");

One more thing

另外类似于AFN的网络请求,我们也可以在方法当中把 block 当成参数传递。

.h文件
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController

-(void)sayHello:(void(^)(NSString * name))hello;

@end

.m 文件
#import "ViewController.h"

@implementation ViewController

-(void)sayHello:(void (^)(NSString *))hello{
    
    hello(@"name");   
}

Swift

①使用别名声明 block

typealias HelloBlock = (_ str:String) -> ()

然后使其成为属性
var block:HelloBlock?

②实现block

self.block = {
    str in
    print(str)        
}

③调用Block

block!("hello")

One more thing

和OC类似,我们在 swift 当中也可以在方法中传递闭包,把闭包当成是参数。

声明方法

func loadRequest(callBack : (_ str:String)->()){
        callBack("hello")
}

调用方法

self.loadRequest { (str) in
    print(str)
}

避免循环引用的问题

另外还需要注意循环引用,有三种方法

一、在闭包外写 weak var weakSelf = self
在内部需要调用 self 的地方使用 weakSelf代替。
二、在闭包内部写[weak self]

self.loadRequest {[weak self] (str) in
    
    self.view.backgroundColor = UIColor.redColor()

    print(str)
}

三、在闭包中写 [unowned self]

self.loadRequest {[unowned self] (str) in
    
    self.view.backgroundColor = UIColor.redColor()

    print(str)
}