如果在ClassA中创建对象,如何在ClassB中观察?

时间:2017-03-26 07:26:04

标签: swift swift3 key-value-observing

我的对象:

private void textBox1_Leave(object sender, EventArgs e)
    {
        ot_price.Text = (float.Parse(tot_qty.Text) * float.Parse(price.Text)).ToString();
    }

//Object to observe struct Text { let savedUserHeader: String let savedUserText: String } 我创建对象的地方:

ClassA

//First Class class A { func somefunc(){ let a = Text(savedUserHeader: "testHeader", savedUserText: "testText") } } 中,我想观察是否创建了一个新对象:

classB

1 个答案:

答案 0 :(得分:1)

<强>代表

您可以使用Delegate模式观察,创建一个名为ADelegate的协议:

protocol ADelegate {
    func didCreateText(text: Text)
}

然后,在A类中添加一个名为delegate的变量,并将Text对象传递到didCreateText(text:)中的somefunc()方法:

//First Class
class A {

    var delegate: ADelegate?

    func somefunc(){
        let a = Text(savedUserHeader: "testHeader", savedUserText: "testText")
        delegate?.didCreateText(text: a)
    }
}

接下来,当您在B中创建对象A时,设置a.delegate = self并实施ADelegate协议:

//Second Class
class B: ADelegate {

    var headerlabel: UILabel!
    var saveUserLabel: UILabel!

    var a = A()

    var text: Text? {
        didSet{
            headerlabel.text = text?.savedUserHeader
            saveUserLabel.text = text?.savedUserText
        }
    }

    init() {
        a.delegate = self
    }

    func didCreateText(text: Text) {
        print("savedUserHeader: \(text.savedUserHeader)")
        print("savedUserText: \(text.savedUserText)")
    }
}

就是这样!在didCreateText(text:)方法中创建对象Text时,将调用方法somefunc()

let b = B()
b.a.somefunc()

通知中心

另一种解决方案是NotificationCenter。在创建Text对象时发布通知:

func somefunc(){
    let a = Text(savedUserHeader: "testHeader", savedUserText: "testText")
    NotificationCenter.default.post(name: Notification.Name("addText"), object: a)
}

在B班观察:

init() {
    NotificationCenter.default.addObserver(self, selector: #selector(observeText(noti:)), name: Notification.Name("addText"), object: nil)
}

@objc func observeText(noti: Notification) {
    if let text = noti.object as? Text {
        print("savedUserHeader: \(text.savedUserHeader)")
        print("savedUserText: \(text.savedUserText)")
    }
}

试试吧:

let b = B()
let a = A()
a.somefunc()

您将看到结果:

savedUserHeader: testHeader
savedUserText: testText