简体   繁体   中英

Swift delegate & protocols

For protocols and delegates to work, do the view controllers have to be adjacent in the stack? The function called by my delegate was working fine until I inserted a new vc in between the vc sending the data and the vc receiving them. (If the answer is, "Of course, you idiot." I'd actually be relieved as I'm really stumped.)

Presumably, you have something like this:

在此处输入图像描述

and your code runs along these lines:

protocol MyCustomDelegate: class {
    func myFunc(_ value: Int)
}

class VC1: UIViewController, MyCustomDelegate {
    
    func myFunc(_ value: Int) {
        print("value: \(value)")
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let vc = segue.destination as? VC2 {
            vc.delegate = self
        }
    }
}

class VC2: UIViewController {
    
    weak var delegate: MyCustomDelegate?
    
    func someAction(_ sender: Any?) -> Void {
        delegate?.myFunc(1)
    }
    
}

Now, you "insert a new VC" :

在此处输入图像描述

So your code in VC1 is no longer segueing to VC2 ... and thus the delegate won't be set.

One approach, not necessarily the best, would be:

  • add a delegate var in VC1A , which is set by VC1
  • when navigating from VC1A to VC2 , pass that delegate along

It could look something like this:

protocol MyCustomDelegate: class {
    func myFunc(_ value: Int)
}

class VC1: UIViewController, MyCustomDelegate {
    
    func myFunc(_ value: Int) {
        print("value: \(value)")
    }
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let vc = segue.destination as? VC1A {
            vc.delegate = self
        }
    }

}

class VC1A: UIViewController {
    
    weak var delegate: MyCustomDelegate?
    
    func someAction(_ sender: Any?) -> Void {
        delegate?.myFunc(1)
    }
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let vc = segue.destination as? VC1A {
            vc.delegate = self.delegate
        }
    }

}

class VC2: UIViewController {
    
    weak var delegate: MyCustomDelegate?
    
    func someAction(_ sender: Any?) -> Void {
        delegate?.myFunc(1)
    }
    
}

If your app flow is simple enough, this would probably work... but, it's not ideal and is prone to problems as your code gets more complex.

You may want to re-think how your code is structured, and how you're trying to manage your data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM