Swift—手写复用池(附代码)

import UIKit

class ViewController: UIViewController {
    let reuseableCellPool = ReusableCellPool(capacity: 5)
    override func viewDidLoad() {
        super.viewDidLoad()
        for i in 0...5 {
            let cell = Cell(name: "\(i)")
            reuseableCellPool.enqueue(withIdentifier: "reusedCell", cell: cell)
        }
        for i in 0...5 {
            if let cell = reuseableCellPool.dequeueReuseableCell(withIdentifier: "reusedCell") {
                cell.printOut()
            }
        }
    }
}
class Cell {
    var name: String
    init(name: String) {
        self.name = name
    }
    func printOut() {
        print("l am cell \(name)")
    }
}

class ReusableCellPool {
    private var reusableCell: [String: [Cell]] = [:]
    private let lock = NSLock()
    private let capacity: Int
    
    init(capacity: Int) {
        self.capacity = capacity
    }
    
    func dequeueReuseableCell(withIdentifier: String) -> Cell? {
        lock.lock()
        defer { lock.unlock() }
        if var cells = reusableCell[withIdentifier], let cell = cells.popLast() {
            reusableCell[withIdentifier] = cells
            return cell
        }
        return nil
    }
    
    func enqueue(withIdentifier: String, cell: Cell) {
        lock.lock()
        if var cells = reusableCell[withIdentifier] {
            if cells.count <= capacity {
                cells.append(cell)
                reusableCell[withIdentifier] = cells
            }
        } else {
            reusableCell[withIdentifier] = [cell]
        }
        lock.unlock()
    }
}

相信大家看完这里,应该对UITableViewCell的复用机制有了更深一步的了解了吧,下面我们一起来看一下UITableView的复用代码吧 

// 假设 tableView 是 UITableView 实例,cellIdentifier 是单元格的重用标识符
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    // 从复用池中获取可重用的单元格
    let cell: UITableViewCell
    if let reusableCell = cellPool.dequeueReusableCell(withIdentifier: cellIdentifier) {
        cell = reusableCell
    } else {
        // 如果复用池中没有可用的单元格,则创建一个新的单元格
        cell = UITableViewCell(style: .default, reuseIdentifier: cellIdentifier)
        //换成我上面的代码就是 cell = Cell(name: "")
    }
    
    // 设置单元格的内容
    // ...
    
    return cell
}

func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    // 在单元格离开屏幕时,将单元格放回复用池中
    cellPool.enqueue(cell, withIdentifier: cellIdentifier)
}

大家喜欢的可以点点关注哈,博主最近会更新滴! 

  • 11
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值