iOS Block与Delegate的用法,各自优缺点及使用场景

版权声明:本文为博主原创文章,未经博主允许不得转载 https://blog.csdn.net/huangshanfeng/article/details/82106580

问题:

你是否有想过在UITableViewCell上把UIButton点击事件回调到UIViewController?你是否有想过在封装Alamofire或者AFNetWorking的时候回调网络数据?

概念:

Block官方解释:

Block objects are a C-level syntactic and runtime feature. They are similar to standard C functions, but in addition to executable code they may also contain variable bindings to automatic (stack) or managed (heap) memory. A block can therefore maintain a set of state (data) that it can use to impact behavior when executed.

You can use blocks to compose function expressions that can be passed to API, optionally stored, and used by multiple threads. Blocks are particularly useful as a callback because the block carries both the code to be executed on callback and the data needed during that execution.

翻译过来:

Block是C语言语法和运行时功能。它们类似于标准C函数,但除了可执行代码之外,它们还可能包含对内存变量的绑定。因此,Block可以维护一组状态(数据),它可以用于在执行时影响行为。

您可以使用Block来组合可以传递给API的函数表达式,可选地存储并由多个线程使用。Block作为回调特别有用,因为Block包含要在回调时执行的代码和执行期间所需的数据。

block官方文档

运用:

block

typealias FirstCellBlock = (_ cell:firstTableViewCell) -> ()

var firstCellBlock:FirstCellBlock?

if let firstCellBlock = self.firstCellBlock {
   _ = firstCellBlock(self)
}

cell.firstCellBlock = {(cell : firstTableViewCell) in
            
    let cellIndexPath = tableView.indexPath(for: cell)
    print("block回调 section:\(cellIndexPath?.section ?? 0), row:\(cellIndexPath?.row ?? 0)")
            
}

完整代码

delegate

protocol FirstCellDelegate:class {
    func firstCellBtnTap(_ cell: firstTableViewCell)  //点击
}

weak var delegate: FirstCellDelegate?

if let delegate = self.delegate {
   delegate.firstCellBtnTap(self)
}

//遵守Delegate FirstCellDelegate
cell.delegate = self

func firstCellBtnTap(_ cell: firstTableViewCell) {
    let cellIndexPath = tableView.indexPath(for: cell)
    print("delegate回调 section:\(cellIndexPath?.section ?? 0), row:\(cellIndexPath?.row ?? 0)")
}

完整代码

总结:

block、delegate作用:

1.能回调传值

2.使对象与对象之间能通信交互

3.改变或传递控制链。允许一个类在某些特定时刻通知到其他类,而不需要获取到那些类的指针。可以减少框架复杂度

 

block优缺点

block优点:

1.省去了写代理的很多代码

2.block 更轻型,使用更简单,能够直接访问上下文,这样类中不需要存储临时数据,使用 block 的代码通常会在同一个地方,这样能连贯读代码

block缺点:

1.block不够安全,使用 block 时稍微不注意就形成循环引用,导致对象释放不了。这种循环引用,一旦出现就比较难检查出来。

2.block效率低,block出栈需要将使用的数据从栈内存拷贝到堆内存

3.在多个通信事件的时候,block显得不够直观也不易维护。 

block使用场景:

在1-2个通信事件的时候用block

delegate优缺点:

delegate优点:

1.delegate更安全, delegate 的方法是分离开的,不会引用上下文,不容易循环引用

2.delegate效率高,delegate只是保存了一个对象指针

3.在多个通信事件的时候,delegate显得直观也易维护。 

delegate缺点:

1.因方法的声明和实现分离开来,代码的连贯性不是很好,没有 block 好读

2.很多时候需要存储一些临时数据

delegate使用场景:

3个以上通信事件用delegate

猜你喜欢

转载自blog.csdn.net/huangshanfeng/article/details/82106580