2016-04-27 22 views
1

在NSViewController子類中組織函數的替代方法?

我目前有一個視圖控制器(命名爲ViewController),它管理我的應用程序的視圖與故事板,由用戶輸入的幾個文本框組成。如果用戶輸入的內容不正確,它會調用一個函數來提醒用戶錯誤(使用NSAlert模式),併爲他們提供一個選項:重置輸入,重置輸入和先前的輸出,或者關閉窗口。

問題是,單獨該警報代碼是大約60行的代碼(用函數來顯示適當的消息),我想將其移動到另一個類 - 的ViewController一個子類,標題爲ErrorResponse,所以它仍然可以訪問用戶界面以適當地重設其輸入(即,清除輸入字符串字段),並執行上面,同時避免在ViewController

的功能的大量壁提到的其他任務我試圖創建的ViewController一個子類,因此用戶界面屬性是繼承的,我可以簡單地訪問它們,但Xcode希望子類使用NSCoder實現init方法。 (據我所知,這是Xcode如何設置故事板或.xib與控制器進行通信,作爲NSViewController類的一部分,但這與我的隱含意義無關)。當我試圖通過nil或默認初始化NSCoder()對象時,我得到了模糊的崩潰。

那麼,有什麼辦法來組織這些功能?或者我應該把它們都放在ViewController中?

編輯:我也有一個名爲ErrorCheck的現有類,它執行檢查以查看是否有任何錯誤。在ViewContoller中,當輸入輸入時,有一條guard語句和一個來自ErrorCheck的方法,如果輸入無效,則調用ErrorResponse中的相應方法。

代碼片段:

class ViewController: NSViewController { 

    // Input and output text fields 
    @IBOutlet weak var inputStr: NSTextField! 
    @IBOutlet weak var outputStr: NSTextField! 

    // Input and output conversion selection 
    @IBOutlet weak var inputSegments: NSSegmentedControl! 
    @IBOutlet weak var outputSegments: NSSegmentedControl! 

    @IBAction func outputIsSelected(sender: NSSegmentedControl) { 

     // Passing all UI elements in (not shown) 
     // Not ideal, want to be global obj (see below code) 
     guard ErrorCheck().stringIsNotEmpty(inputStr.stringValue) else { 
      ErrorResponse().invalidEmptyInput() 
      return 
     } 

     // 0 = DNA, 1 = mRNA, 2 = English 
     if (inputSegments.selectedSegment == 0) { 
      checkPossibleConversionAndConvertDNA() 
     } else if (inputSegments.selectedSegment == 1) { 
      checkPossibleConversionAndConvertmRNA() 
     } else if (inputSegments.selectedSegment == 2) { 
      checkPossibleConversionAndConvertEnglish() 
     } 

    } 
} 

如果我不繼承視圖控制器,還有一個問題:我不能定義全局對象錯誤響應,因爲我不能在同一通過UI值因爲它們正在被初始化,所以目前我已經在每個相應的函數中初始化了一個ErrorCheck對象......並且它很亂。

+0

由於您沒有發佈您的代碼,我無法給出具體的答案。但我想你可以把你的警報代碼放入NSAlert的新類類中,並使用協議與ViewController進行通信。 – luiyezheng

+0

@luiyezheng更新w/code示例 – Graystripe

回答

0

我最終只是將方法移入ViewController。不是最漂亮的,但它是功能性的。

相關問題