2016-07-12 103 views
0

我目前正在處理一個項目。它可能會在下面的多個控制器中有重複的代碼。控制器中的重複代碼


控制器A

class A: UIViewController, AVCaptureMetadataOutputObjectsDelegate { 
    // about 50~70 lines of codes 
    @IBAction func scanButtonTapped { 
     // used self (as AVCaptureMetadataOutputObjectsDelegate) 
     // used view 
     // called presentViewController(...), which is a func in UIViewController 
    } 
} 

控制器B

class B: UIViewController, AVCaptureMetadataOutputObjectsDelegate { 
    @IBAction func scanButtonTapped { 
     // will need same logic as in Controller A 
    } 
} 

我當前的解決方案是具有另一個類C,並移動所述複製碼進去。但是,如果我這樣做,控制器可以投射到AVCaptureMetadataOutputObjectsDelegate,但不投射到UIViewController

class C { 
    func btnTapped (view: UIView, controller: AnyClass) { 
     // logic is here 
     // controller can cast to AVCaptureMetadataOutputObjectsDelegate 
     // but controller cannot cast to UIViewController 
    } 
} 

所以A和B將具有

class A { 
    @IBAction func scanButtonTapped { 
     let c = C() 
     c.btnTapped(view, self) 
    } 
} 

我的問題是,如果有可能投控制器爲UIViewController。還有另一種方法來正確地重構代碼嗎?

+0

你爲什麼不這樣做'類C:的UIViewController,AVCaptureMetadataOutputObjectsDelegate {...}'然後'A級:C {'和'B類:C {' ? – luk2302

回答

2

那麼擴展AVCaptureMetadataOutputObjectsDelegate協議並通過協議擴展(POP方法)創建默認實現呢?

protocol ScanButtonClickable: AVCaptureMetadataOutputObjectsDelegate { 
    func btnTapped() // this line is optional 
} 

extension Clickable where Self: UIViewController { 
    func btnTapped() { 
     // logic is here 
    } 
} 

class A: UIViewController, ButtonClickable { 
... 
} 

class B: UIViewController, ButtonClickable { 
... 
} 
+0

謝謝JMI。這非常有幫助。 – Jimmy

0

試試這個:

//declare your default method to be used across classes 
protocol MyProtocol { 
    func myFunc() 
} 

//provide the implementation of your default behavior here in myFunc() 
extension MyProtocol { 
    func myFunc() { 
     print("Default behavior") 
} 
} 

class A: MyProtocol { 

} 

class B: MyProtocol { 

} 

let a = A() 
a.myFunc() 

let b = B() 
b.myFunc() 

//prints 
Default behavior 
Default behavior 
相關問題