2017-06-22 56 views
2

我正在學習對委託模式的深入瞭解。 iOS中的很多代碼示例使用了兩個ViewControllers,其中涉及prepare(for segue:...)沒有故事板或segue的委託模式

我希望我的程序只使用一個ViewController與代表協議,但沒有segue或故事板。 ViewController有一個按鈕來執行簡單的委託方法,比方說添加一個數字。

ViewController類:

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 
} 
} 

專用Delegate類:

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

class ClassDelegate: NSObject { 
weak var delegate: theDelegate? 

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

回答

1

從@PhillipMills答案應該是正確的,只是從thisthis添加有關命名約定的一些注意事項,爲您獲得更好的代碼質量。

  • 您應該使用類型(和協議),小寫字母大寫字母一切
  • 沒有必要,除非你想從ObjC世界的東西,無論是ObjC工作或使用志願
  • 從NSObject的繼承
+0

謝謝大家的回覆。 @PhillipMills我不是很確定你的意思,你是說我沒有正確使用委託模式? – Tony

3

如果您的視圖控制器是委託,那麼你的類命名是混亂的。你所說的ClassDelegate不會是任何類型的代表,而是使用代表的「工人」。但是....

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

哦,我明白了。我想我反過來了。所以該類採用的協議是真正的委託類,而我所謂的ClassDelegate只是協議,可能應該重命名爲ClassProtocol是否正確?對不起,英語不是我的第一個語言。 – Tony

+0

'ClassDelegate'只與協議有關,因爲它使用它。真的,它沒有理由被稱爲「委託」或「協議」。考慮一個表格視圖;它使用委託,但我們沒有以與委託協議相關的任何方式命名它。 –

+0

我明白了。非常感謝幫助我解決這個問題。 :) – Tony