为什么viewDidLoad()会被调用两次?

时间:2015-09-26 10:52:13

标签: ios swift uitableview

出于某种原因,我的数据被保存两次到模型。为什么viewdidload会跑两次?这个控制器的目的是成为一个记分牌。它由使用核心数据的数据填充。我试过删除tablecontroller并添加一个新的。

import UIKit
class ScoreboardTableViewController: UITableViewController {

    var model = scoreboardModel.sharedInstance
    var numbers = [9,12,9]// [Int]()
    var timer = "k"
    var date = "thedateToday"



    override func viewDidLoad() {
        super.viewDidLoad()
        var count = numbers.count
        var x = String(count)


        if(timer != "k"){
            model.saveScoreboard(date, numsMemorized: x,time: timer)
            println("saved!")
        }
        model.getScoreboards()

        }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()

    }

      // MARK: - Table view data source


    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return model.scoreboard.count
    }


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

        let cell = tableView.dequeueReusableCellWithIdentifier("Cellll", forIndexPath: indexPath) as UITableViewCell

        let score = model.getScore(indexPath)
        cell.textLabel!.text = ("\(score.numsMemorized) | \(score.time)")

        return cell
    }

}

分段到ScoreboardTableViewController的视图是:

import UIKit

class PracticeReciteController: UIViewController, UITextFieldDelegate {

var theTime = ""

@IBOutlet weak var howManyCorrect: UILabel!

var numbers = [9,12,9]
var x = 0

@IBOutlet weak var textField: UITextField!

var howManyCorrectNum = 0

override func viewDidLoad() {
    super.viewDidLoad()



    var outof = numbers.count
    howManyCorrect.text = "\(howManyCorrectNum) / \(outof)"

    textField.delegate = self;
    textField.addTarget(self, action:"edited", forControlEvents:UIControlEvents.EditingChanged)

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}



func edited() {

    //[todo] if on last number in array & correct. endgame/collectscore
    var userInput = textField.text.toInt()

    if numbers[x] == userInput{

        if x+1 == numbers.count{


            performSegueWithIdentifier("scoreboardIdentifier", sender: self)

        }
        //println("correct")
        x++

        howManyCorrect.text = String(x) + "/" + String(numbers.count)

            //I set here timer so if user enter correct input then it will remove text after some time
        var timer = NSTimer.scheduledTimerWithTimeInterval(0.8, target: self, selector: Selector("resetText"), userInfo: nil, repeats: false)
    }else if userInput?.isDouble() == numbers[x].isDouble(){
        println("incorrect")
    }
    else{
        println("huh?")

    }
}
//This method will call after some time use if user enter correct input
func resetText(){
    textField.text = ""
}




override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {


    var DestViewController = segue.destinationViewController as ScoreboardTableViewController

    DestViewController.numbers = numbers
    DestViewController.timer = theTime


}

} 

2 个答案:

答案 0 :(得分:2)

这个问题之前已被多次回答: viewDidLoad getting called twice on rootViewController at launch

viewDidLoad is called twice

无论如何,一个重要的建议是:不要在viewDidLoad中放置任何会破坏您的应用/数据的代码。 {C> 1}}假设在ViewController的生命周期中只被调用一次

答案 1 :(得分:0)

这是个老问题,但是我发现是..

在Swift中,如果您访问uiviewcontroller的视图,例如

enter @IBOutlet weak var searchTextField: UITextField! {
    didSet {
        self.searchTextField.borderStyle = .none
        self.searchTextField.keyboardType = .default
        self.searchTextField.placeholder = "Search"
        let width = (self.view.frame.width - 114)
        self.searchTextField.frame = CGRect.init(origin: searchTextField.frame.origin, size: CGSize.init(width: width, height: searchTextField.frame.height))
    }
}

然后它将首先在该阶段调用viewDidLoad,然后将其作为生命周期调用。