在展开Optional值时意外发现nil

时间:2014-12-29 13:13:56

标签: ios swift nsuserdefaults

我对编程很陌生,而且我已经在网上寻找了几天,试图解决我在Swift编程中遇到的这个问题。我是所有这一切的新手;而且,我已经尽力尝试自己寻找解决方案。但是,经过这段令人沮丧的时间之后,我可以向专家们询问。

我尝试使用的代码是:

import UIKit
class ViewController: UIViewController {

    var myTime: AnyObject = NSUserDefaults() //creates a var called myTime that can be used to save the time parameter.
    var timer = NSTimer() // creates a variable used by the timer loop.

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        myTime = NSUserDefaults.standardUserDefaults().objectForKey("two")! //sets timer value to last saved value

        if (myTime as NSNumber == 0){ //if the initial value doesnt exhist the if statement creates one.
            NSUserDefaults.standardUserDefaults().setInteger(0, forKey: "two") //sets timer to zero and saves parameter
        }

        timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("action"), userInfo: nil, repeats: true) // Creates a timer at 1 second time interval which then performs function called 'action' and will continue until boolean is set to false or NSTimer is invalidated.
    }

    func action(){

        myTime = Int(myTime as NSNumber) + 1 // increases myTime by 1
        println(myTime) //println(time) // prints myTime

        NSUserDefaults.standardUserDefaults().setInteger(myTime as Int, forKey: "two") // saving variable two with value of 2
        NSUserDefaults.standardUserDefaults().synchronize() // Added synchronize as suggested by LAMMERT WESTERHOFF
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

我收到的错误消息是:

  

致命错误:在展开Optional值时意外发现nil   (LLDB)

话说:

  

主题1:EXC_BAD_INSTRUCTION(代码= EXC_1386_INVOP,子代码= 0x0)

如果有人能告诉我自己做错了什么以及如何解决我的问题,我会非常感激。

1 个答案:

答案 0 :(得分:2)

此处发生错误

myTime = NSUserDefaults.standardUserDefaults().objectForKey("two")!

这是因为您尝试将可选值(不能为n)分配给非可选变量。

要解决此问题,您需要为键设置对象"两个"在您获取此对象或使myTime变量可选

之前

还要检查在将其转换为NSNumber

之前应将其检查为nil的值

此代码应该可以正常工作

*import UIKit
class ViewController: UIViewController {

//here I added ? which means optional value
    var myTime: AnyObject? = NSUserDefaults() //creates a var called myTime that can be used to save the time parameter.
    var timer = NSTimer() // creates a variable used by the timer loop.

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

// here I removed ! because value for key "two" may not been set so it is optional value
        myTime = NSUserDefaults.standardUserDefaults().objectForKey("two") //sets timer value to last saved value

//here we check myTime object for nil before converting to NSInteger and checking for 0
        if ( myTime == nil || myTime as NSNumber == 0){ //if the initial value doesnt exhist the if statement creates one.
            NSUserDefaults.standardUserDefaults().setInteger(0, forKey: "two") //sets timer to zero and saves parameter
        }

        timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("action"), userInfo: nil, repeats: true) // Creates a timer at 1 second time interval which then performs function called 'action' and will continue until boolean is set to false or NSTimer is invalidated.
    }

    func action(){

        myTime = Int(myTime as NSNumber) + 1 // increases myTime by 1
        println(myTime) //println(time) // prints myTime

        NSUserDefaults.standardUserDefaults().setInteger(myTime as Int, forKey: "two") // saving variable two with value of 2
        NSUserDefaults.standardUserDefaults().synchronize() // Added synchronize as suggested by LAMMERT WESTERHOFF
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}*