2016-10-14 4 views
0

위임을 사용하고 있으며 동일한 클래스를 두 가지 방법으로 사용하고 있습니다.Delegating Object를 식별하는 방법

protocol ColorSwitchDelegate { 
     func colorSwitched(picker: ColorSwitch, color: ColorChoice) 
    } 

    class ColorSwitch: UIView {  
     var delegate: ColorSwitchDelegate? 

    func doSomething() { 
    delegate?.colorSwitched(picker: self, color: color) 
    } 
    } 

    class SettingsViewController: UIViewController, ColorSwitchDelegate { 

    @IBOutlet weak var myView1: ColorSwitch! 
    @IBOutlet weak var myView2: ColorSwitch! 

    func viewWillAppear(_ animated: Bool) { 

    myView1.delegate = self 
    myView2.delegate = self 
    } 



    func colorSwitched(picker: ColorSwitch, color: ColorChoice) { 
      // I want to find out if myView1 or myView2 is the delegating object 
    } 
    } 

어떤 뷰 (myView1 또는 myView2)가 위임자인지 식별하고 싶습니다. 나는 ColorSwitch 클래스에 태그를 추가 할 수 있지만 이것은 우아하지 않게 보입니다. 더 좋은 방법이 있습니까?

+0

당신은 picker == self.myView1 {}인지 확인할 수 있습니다. 하지만 태그를 추가하는 것이 가장 좋습니다. – Sahil

+0

죄송합니다. 코드를 명확히했습니다. myView1과 myView2 모두 대리자가 SettingsViewController로 설정되어 있습니다. 그래서 나는 nil을 검사 할 수 없다. – Pete

+0

'picker === myView1 {// 1로 처리} else if picker === myView2 {// do something with 2}' – vacawama

답변

1

identity opeartor ===를 사용하여 직접 colorSwitched을 체크인 할 수 있습니다. 두 개의 객체 참조가 모두 동일한 객체 인스턴스를 참조하는지 테스트합니다.

func colorSwitched(picker: ColorSwitch, color: ColorChoice) { 
    if picker === self.myView1 { 

    //myView1 
    } else { 

    //myView2 

    } 

}