2017-04-13 51 views
1

在我的項目中,我有一些代表可以很好地處理返回的數據,但我想在代理方法中添加一些子視圖或做任何事情,使用相同方法的代碼都可以! 我的另一個問題也與代表相關: 這發生在一些代表。代表沒有迴應,但我在網上發現了一個非常奇怪的修復,我需要知道爲什麼會發生這種情況,以及爲什麼這個修復工作正常!swift 3中的代表不執行查看相關代碼

我的第一個觀點:

protocol SomeDelegate { 
    func someMethod() 
} 

class FirstViewClass { 
    //in init or didLoad method 
    var delegate: SomeDelegate? 

    // THIS DELEGATE WON'T WORK BUT WHEN I ADD THIS LINE IT WORKS FINE(IT STILL HAS THE ABOVE PROBLEM) 
    self.delegate = SecondViewClass() 

    //in some custom method 
    self.delegate?.someMethod(); 
} 

我的第二個觀點:

class SecondViewClass : SomeDelegate { 
    var firstView = FirstViewClass() 

    // this is in init or didLoad method 
    firstView.delegate = self 

    //this is in some custom method 
    someMethod() 
} 

回答

0

簡單的工作原型:

protocol SomeDelegate { 
    func someMethod() 
} 

class FirstViewClass { 
    var delegate: SomeDelegate? 
} 

class SecondViewClass : SomeDelegate { 
    var firstView = FirstViewClass() 

    func someMethod() { 
     print("called via delegate") 
    } 
} 

var firstClass = FirstViewClass() 

var secondClass = SecondViewClass() 

firstClass.delegate = secondClass 

firstClass.delegate?.someMethod()