2016-03-07 80 views
0

即時創建一個RPN計算器。當按下磁帶按鈕繼續播放第二個VC時,我需要代碼的幫助才能查看我所有的計算結果。當按下磁帶按鈕時,它將顯示輸入的計算結果。第二個視圖控制器中的功能。我知道編程。我在第一個VC中實施了prepareforsegue。我不知道如何堆棧傳遞給numberOfRowsInSectionSegue:顯示堆棧到第二個視圖控制器

計算器引擎

class CalculatorEngine :NSObject 

{ 

    var operandStack = Array<Double>() 

    func updatestackWithValue(value: Double) 
    { 
     self.operandStack.append(value) 
    } 


    func operate(operation: String) ->Double 
    { 

     switch operation 
     { 
     case "×": 
      if operandStack.count >= 2 
     { 
     return self.operandStack.removeLast() * self.operandStack.removeLast() 

第二個視圖

class SecondVCViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { 

var array = [""] 

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    return array.count 
} 

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 

    let cell = tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell 

    cell.textLabel?.text = array[indexPath.row] 

    return cell 
+0

您的'CalculatorEngine'實例在哪裏? –

+0

我還沒有添加它 –

回答

1

一個簡單的解決辦法可能是使用Singleton pattern。這是一個design pattern,旨在用於最多隻能有一個實例的對象。我假設CalculatorEngine這個類是真的。

單身斯威夫特很簡單:只需添加以下到您的CalculatorEngine類:

static let sharedInstance : CalculatorEngine = CalculatorEngine()

這將創建可以輕鬆地從任何地方的應用程序進行訪問的類級屬性 - 可以獲取sharedInstance以下列方式:

let engine = CalculatorEngine.sharedInstance

這將允許您訪問計算引擎,而不必擔心經過的g在各種segue方法中來回引用。

作爲旁註,Singleton模式有時被認爲是反模式,因爲在複雜的應用程序中,它可能難以正確模擬類進行測試,並且還可以增加應用程序中可變全局狀態的數量。但如果明智地使用它,那就沒問題 - 當然它非常整齊地適合您的要求。它也烤成可可觸摸 - UIApplication.sharedApplication是一個單身人士。

+0

您可以省略'sharedInstance'聲明中的類型聲明(「:CalculatorEngine」),因爲它將由'CalculatorEngine()' –

相關問題