没有故事板或 segue 的委托模式

Delegate pattern without storyboard or segue

我正在学习以深入了解委托模式。 iOS中的很多代码示例使用了两个ViewControllers,其中涉及prepare(for segue:...).

我希望我的程序只使用一个 ViewController 带有委托协议但没有 segue 或故事板。 ViewController 有一个按钮来执行一个简单的委托方法,比方说添加一个数字。

ViewController Class:

class ViewController: UIViewController, theDelegate {

override func viewDidLoad() {
    super.viewDidLoad()
}

// It is here I got stuck
// How do I set delegate = self without out involving segue or the     storyboard at all? Do I need to instantizate the dedecated delegate class and how?
// To conform to delegate -- theDelegate
func add(num: Int) {
    // Output result on ViewController
}

func minus(num: Int) {
    // Output result on ViewController
}
}

敬业DelegateClass:

protocol theDelegate: class {
func add(num: Int)
func minus(num: Int)
}

class ClassDelegate: NSObject {
weak var delegate: theDelegate?

func x() {
    delegate?.add(num: 100)
}
}

如果您的视图控制器是委托,那么您的 class 命名会令人困惑。您所说的 ClassDelegate 不会是任何类型的委托,而是 "Worker" 使用 委托。然而....

var worker = ClassDelegate()
override func viewDidLoad() {
    super.viewDidLoad()
    worker.delegate = self
    worker.x()
}

@PhillipMills 的回答应该是正确的,只是添加了一些关于 this and 的命名约定的注释,以便您获得更好的代码质量。

  • You should use uppercase for types (and protocols), lowercase for everything else
  • No need to inherit from NSObject unless you want something from the ObjC world, whether working with ObjC or use KVO