我试图在NSUserDataStorage中存储一组数字。我做错了什么?谢谢。 导入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.
}
}
我试图这样做,以便在加载视图时,它从永久存储中获取数据,将数组设置为等于它,并且当用户玩游戏时,当他点击结束按钮时,它会获取数据,并将其存储在数组中,然后将其存储到永久存储中。如果不使用Core Data,我该怎么做?
答案 0 :(得分:1)
您几乎已经了解了NSUserDefaults
的想法 - 只需根据需要进行读写即可。我总是想把它抽象成具有直观界面的方法(甚至单独的对象),如save
和load
。
如果您的数据变得更加复杂,您可能需要考虑使用NSKeyedArchiver
和NSCoding
将数据写入设备上的文件,以便轻松地序列化和反序列化。
有关详情,请参阅此 NSHipster Article 。
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 )
}
}