viewcontroller 中的委托未从单例中触发

Delegate not firing from singleton in viewcontroller

我正在单例中存储一个 prizeArray。我已经定义了一个协议和一个委托。如果我创建 class(而不是 viewController),当我更改 prizeArray 的值时,委托将按预期触发。但是,在我的 viewController 中,我无法解雇代表。你能指出我做错了什么吗?非常感谢。

这是单例 AppData class

import Foundation

protocol AppDataDelegate {
    func didChange(_ prizeArray: Array<Prize>)
}

class AppData
{
    static let shared = AppData()
    var delegate: AppDataDelegate?
    var parsedPrizes:[Prize] = []
    
    private init() {}
    
    func changeThis(newArray: [Prize]) {
        parsedPrizes = newArray
        print("AppData got parsedPrizes")
        delegate?.didChange(newArray)
    }
}

import UIKit
import CoreData

class GameBoard: FPBViewController, AppDataDelegate {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        AppData.shared.delegate = self
    }

    func didChange(_ prizeArray: Array<Prize>) {
        print("data via the delegate prizeArray: \(prizeArray.count)")
    }
}



还有其他 class 使用 AppData 的单例委托吗?如果是这样,也许这就是为什么......您可能将另一个 ViewController 重新分配给该代表并且 GameBoard 停止收听。

编辑; 为了能够通知多个 classes,你需要像这样保留这些 classes 的多个实例:

import Foundation

protocol AppDataDelegate {
    func didChange(_ prizeArray: Array<Prize>)
}

class AppData
{
    static let shared = AppData()
    var delegates: [AppDataDelegate] = [] <=========== notify every class that listens
    var parsedPrizes:[Prize] = []
    
    private init() {}
    
    func changeThis(newArray: [Prize]) {
        parsedPrizes = newArray
        print("AppData got parsedPrizes")

        delegates.forEach { delegate in <===========
            delegate.didChange(newArray)
        }
    }
}

import UIKit
import CoreData

class GameBoard: FPBViewController, AppDataDelegate {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        AppData.shared.delegates.append(self) <===========
    }

    func didChange(_ prizeArray: Array<Prize>) {
        print("data via the delegate prizeArray: \(prizeArray.count)")
    }

    @IBAction func closeVC(_ sender: Any) {
        if let index = AppData.shared.delegates.firstIndex(where: { [=10=] === self }) {
            AppData.shared.delegates.remove(at: index)
        }
    
        // -------------------------------------------
    
        self.dismiss(animated: true, completion: nil)
    }
}