Issue with NSDataStorage in simple reflex test gam

2019-05-20 04:17发布

问题:

I'm trying to store an array of numbers in NSUserDataStorage..what am I doing wrong? Thanks. import UIKit

class ViewController: UIViewController {
var arr = [Int]()
var timer = NSTimer()
var countdowntimer = NSTimer()
var count = 0
var countdown = Int(arc4random_uniform(4000) + 1000)
var highscore:Int!


@IBOutlet weak var beginButton: UIButton!





@IBOutlet weak var startButton: UILabel!
@IBOutlet weak var highScoreButton: UILabel!
@IBOutlet weak var timerLabel: UILabel!
@IBOutlet weak var backgroundImage: UIImageView!

func updateTime() {
    countdown = countdown - 1
    if countdown <= 0 {
        startButton.textColor = UIColor.blackColor()
        startButton.text = "Tap Now!"
        countdowntimer.invalidate()
        backgroundImage.image = UIImage(named: "red")
        count = 0
        Timer()
    }
}

func Timer() {
    timer = NSTimer.scheduledTimerWithTimeInterval(0.001, target:self, selector:Selector("reflexTest"), userInfo:nil, repeats: true)

}

func reflexTest() {
    count = count + 1
    timerLabel.text = "\(count) ms"
}




@IBAction func beginTapped(sender: AnyObject) {
    if startButton.text == "Tap when the Color Changes" {
        startButton.text = "You tapped too early!"
        countdowntimer.invalidate()
        countdown = Int(arc4random_uniform(4000) + 1000)
    } else {
    if count == 0 {
    countdowntimer = NSTimer.scheduledTimerWithTimeInterval(0.001, target: self, selector: Selector("updateTime"), userInfo: nil, repeats: true)
    startButton.text = "Tap when the Color Changes"
        countdown = Int(arc4random_uniform(4000) + 1000)
        timerLabel.text = "\(count) ms"
    } else {
        timer.invalidate()
        backgroundImage.image = UIImage(named: "green")
        startButton.text = "Tap to Begin"
        arr.append(count)
        count = 0
        highscore = minElement(arr)
        highScoreButton.text = "Best: \(highscore)"
        self.viewDidLoad()
        }

    }

}





override func viewDidLoad() {
    super.viewDidLoad()
    NSUserDefaults.standardUserDefaults().setObject(arr, forKey: "data")
    arr = NSUserDefaults.standardUserDefaults().objectForKey("data") as! [Int]
    println(arr)
            // Do any additional setup after loading the view, typically from a nib.
}

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

}

Im trying to make it so that when the view is loaded, it takes the data from permanent storage, sets the array equal to it, and as the user plays the game, when he clicks the end button, it takes the data, and stores it back in the array, and then takes that into permanent storage. How may I do this without using Core Data?

回答1:

You've almost got the idea with NSUserDefaults—just read and write as needed. I always like to abstract that away into methods (or even separate objects) that have an intuitive interface like save and load.

If your data gets more complex, you may want to look into writing data to a file on the device with NSKeyedArchiver and NSCoding in order to serialize and deserialize easily.

See this NSHipster Article for more info on that.

class ViewController: UIViewController {
    var arr = [Int]()

    let kDefaultsKey = "com.mycompany.myapp.numbers"

    override func viewDidLoad() {
        super.viewDidLoad()
        self.loadDefaults()
    }

    func randomNumner() -> Int {
        return Int(arc4random() % 100)
    }

    @IBAction func buttonTapped(sender: AnyObject) {
        arr.append( randomNumber() )
        self.saveDfeaults()
    }

    func loadDefaults() {
        if let savedArray = NSUserDefaults.standardUserDefaults().objectForKey( kDefaultsKey ) as? [Int] {
            self.arr = savedArray
        }
    }

    func saveDfeaults() {
        NSUserDefaults.standardUserDefaults().setObject( self.arr, forKey: kDefaultsKey )
    }
}