简体   繁体   中英

Why is viewDidLoad() getting called twice?

For some reason my data is being save twice to the model. why is viewdidload running twice? this controller purpose is to be a scoreboard. it is populated by data using core data. Ive tried deleting the tablecontroller and adding a new one.

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
    }

}

The view that segues to the ScoreboardTableViewController is:

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


}

} 

The question was being answered many times before : viewDidLoad getting called twice on rootViewController at launch

viewDidLoad is called twice

Anyway, one important advice for you: don't put any code that will broke your app/data in viewDidLoad . The viewDidLoad not assumed to be called only once in ViewController's lifecycle

This is old issue, but what I found is ..

In Swift, if you access the view of uiviewcontroller like

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))
    }
}

Then it will call viewDidLoad in that stage first, then it will call viewDidLoad as lifecycle.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM