簡體   English   中英

不能通過委托從另一個類執行方法?

[英]Can not execute method from another class by delegate?

我正在使用 swift 5.1,不知道 swift 版本是否使它成為不可能。

我在 swiftA.swift 和 SwiftB.swift 中創建了類,我想在 SwiftA.swift 中執行方法。

swiftA.swift:

class MySchoolA : CaculateADelegate {
func executeCaculate(_ MyClass,caculateTheNumber index:Int) -> Int {
    return 80
 }
}

並在 swiftB.swift

protocol CaculateADelegate: AnyObject {
    func executeCaculate(_ MyClass,caculateTheNumber index:Int) -> Int
}

class MyClassB {
    weak var delegate:CaculateADelegate?
    init(){
        let num = delegate?.executeCaculate(self,0)
    }
}

變量 num 始終為零,哪里錯了?

謝謝你。

在 B 類的init中,委托nil

 weak var delegate:CaculateADelegate?

所以如果你這樣做

 let bC = MyClassB() // here it's nil
 bC.delegate = self // here it has a value 

——

所以為了工作,你可以通過在init發送委托來做到這一點

class MySchoolA : CaculateADelegate {
    func executeCaculate(_ ff:MyClassB,caculateTheNumber index:Int) -> Int {
    return 80
 }
}

protocol CaculateADelegate: AnyObject {
    func executeCaculate(_ ff:MyClassB,caculateTheNumber index:Int) -> Int
}

class MyClassB {
    weak var delegate:CaculateADelegate?
    init(_ del:CaculateADelegate){
        self.delegate = del
        let num = delegate?.executeCaculate(self,caculateTheNumber: 0)
        print(num)
    }
}

測試這個

MyClassB(MySchoolA()) // will print 80

您沒有在 swiftA.swift 中將委托引用到 self

在 swiftA.swift 類中,您當時有 swiftB 類的實例,請執行swiftB.delegate = self並在 swiftA 類中實現協議

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM