2016-03-07 69 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()' –

相关问题