2015-04-27 45 views
0

我在IOS中使用過一個成功的Singleton,但同樣的方法在watchkit中不適合我...任何想法爲什麼我的第二個界面控制器顯示0(初始化值)而不是在第一個界面控制器中輸入的數字?使用Singleton在Watchkit中傳遞數據

class Singleton { 

static let instance = Singleton() 

var salesPriceAsInt: Int = 0 

}

import WatchKit 
import Foundation 


class InterfaceController: WKInterfaceController { 

    override func awakeWithContext(context: AnyObject?) { 
     super.awakeWithContext(context) 

     // Configure interface objects here. 
    } 

    var salesPrice = "" 


    @IBOutlet weak var salesPriceLabel: WKInterfaceLabel! 

    func addCharacter(char: String) { 
     salesPrice += char 
    } 


    @IBAction func zeroButton() { 
     addCharacter("0") 
     salesPriceLabel.setText(salesPrice) 
    } 

    @IBAction func oneButton() { 
     addCharacter("1") 
     salesPriceLabel.setText(salesPrice) 
    } 

    @IBAction func twoButton() { 
     addCharacter("2") 
     salesPriceLabel.setText(salesPrice) 
    } 

    @IBAction func threeButton() { 
      addCharacter("3") 
     salesPriceLabel.setText(salesPrice) 
    } 

    @IBAction func fourButton() { 
      addCharacter("4") 
     salesPriceLabel.setText(salesPrice) 
    } 

    @IBAction func fiveButton() { 
      addCharacter("5") 
     salesPriceLabel.setText(salesPrice) 
    } 

    @IBAction func sixButton() { 
      addCharacter("6") 
     salesPriceLabel.setText(salesPrice) 
    } 

    @IBAction func sevenButton() { 
      addCharacter("7") 
     salesPriceLabel.setText(salesPrice) 
    } 

    @IBAction func eightButton() { 
      addCharacter("8") 
     salesPriceLabel.setText(salesPrice) 
    } 

    @IBAction func nineButton() { 
      addCharacter("9") 
     salesPriceLabel.setText(salesPrice) 
    } 


    @IBAction func segueButton() { 
      Singleton.instance.salesPriceAsInt = salesPrice.toInt()! 
      salesPriceLabel.setText("\(Singleton.instance.salesPriceAsInt)") 
    } 

import WatchKit 
import Foundation 


class SecondPageInterfaceController: WKInterfaceController { 



    @IBOutlet weak var totalSaleCommissionLabel: WKInterfaceLabel! 


    override func awakeWithContext(context: AnyObject?) { 
     super.awakeWithContext(context) 

    } 

    @IBAction func secondPageButton() { 
     totalSaleCommissionLabel.setText("\(Singleton.instance.salesPriceAsInt)") 

    } 







    override func willActivate() { 
     // This method is called when watch view controller is about to be visible to user 
     super.willActivate() 

    } 

    override func didDeactivate() { 
     // This method is called when watch view controller is no longer visible 
     super.didDeactivate() 

    } 

回答

1

原來,辛格爾頓有效,哪些沒有被啓用按鈕,兩者(1)實體店的辛格爾頓和(2)順着接下去我的第二個界面控制器爲了解決這個問題,我搬到

Singleton.instance.salesPriceAsInt = salesPrice.toInt()! 

到didActivate方法