首页 > 解决方案 > 委托函数中的数组为空

问题描述

我刚刚实现了这个协议委托构造。但是什么都出错了。我按下自定义 UITableViewCell 中的删除按钮,我想删除数组中的一个项目。我到达了委托函数,我可以打印 id。但是数组是空的(nil)。什么地方出了错?

protocol KonfigDataDelegate: class {
    func deleteItem(id: UUID)
}

class MyClass {

    var Bezeichnung: Sting = ""
    ...
    
}

class ViewControllerKonfiguration: UIViewController, UITableViewDelegate, UITableViewDataSource, KonfigDataDelegate {
    
    var myArray: [MyClass] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
        ...
        myArray = loadAnyDataInArray()
        print(myArray.count) --> 3 elements in array
        ...
    }    
    
    func deleteItem(id: UUID) {
        print("ID: \(id)") --> prints my id
        print(myArray.count) --> 0 - Why is my array empty?
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {        
        var cell: UITableViewCell
        cell = tableView.dequeueReusableCell(withIdentifier: "tvcMahlzeit", for: indexPath) as! TVCKonfigMahlzeit
        (cell as! TVCKonfigMahlzeit).edBezeichnung.text = myArray[indexPath.row]
        (cell as! TVCKonfigMahlzeit).delegate = self

    }   
    
}

class TVCKonfigMahlzeit: UITableViewCell {

    var id: UUID?
    weak var delegate: KonfigDataDelegate?
       
    @IBAction func buttonDeletePresed(_ sender: Any) {
        var vc = ViewControllerKonfiguration()
        self.delegate = vc as KonfigDataDelegate
        delegate?.deleteItem(id: id!)
    }
 
}

标签: swiftuitableviewdelegatesprotocols

解决方案


当我删除这些行时,它可以工作。我在这里创建了一个新的 ViewControllerKonfiguration 实例,那里的数组是空的。

    @IBAction func buttonDeletePresed(_ sender: Any) {
        remove this ––> var vc = ViewControllerKonfiguration()
        remove this ––> self.delegate = vc as KonfigDataDelegate
        delegate?.deleteItem(id: id!)
    }

推荐阅读