Segue:将堆栈显示到第二个View Controller

时间:2016-03-07 14:00:40

标签: ios xcode swift swift2

我在swift中创建一个RPN计算器。当按下磁带按钮以切换到第二个VC时,我需要帮助代码查看我的所有计算。按下磁带按钮时,将显示输入的计算。第二个视图控制器中的功能。我知道编程。我在我的第一个VC中实现了prepareforsegue。我不知道如何将堆栈传递给numberOfRowsInSection

计算器引擎

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

1 个答案:

答案 0 :(得分:1)

一个简单的解决方案可能是使用Singleton pattern。这是一个design pattern,旨在用于最多只能包含一个实例的对象。我假设CalculatorEngine类是正确的。

Swift中的单身人士很简单:只需将以下内容添加到CalculatorEngine课程中:

static let sharedInstance : CalculatorEngine = CalculatorEngine()

这创建了一个类级别属性,可以从应用程序的任何位置轻松访问 - 您可以通过以下方式获取sharedInstance:

let engine = CalculatorEngine.sharedInstance

这将允许您访问计算器引擎,而无需担心在各种segue方法中来回传递引用。

作为旁注,Singleton模式有时被视为反模式,因为在复杂的应用程序中,它可能使得很难正确地模拟类以进行测试,并且还可以增加应用程序中可变全局状态的数量。但如果明智地使用,那就没关系 - 当然它非常适合你的要求。它也融入了Cocoa Touch - UIApplication.sharedApplication是一个单身人士。

相关问题