Dharmesh Rupani
Dharmesh Rupani

Reputation: 1007

ios - fatal error: unexpectedly found nil while unwrapping an Optional value (lldb)

I was using an UIViewController in Swift but I get it when I try to persist the data and trying to retrieving it to back in application.

import UIKit

class ViewController: UIViewController {

    @IBOutlet var linefields:[UITextField]!

    func dataFilePath() -> String {
        let paths = NSSearchPathForDirectoriesInDomains(
            NSSearchPathDirectory.DocumentDirectory,
            NSSearchPathDomainMask.UserDomainMask, true)
        let documetnDirectory = paths[0] as! NSString
        return documetnDirectory.stringByAppendingPathComponent("data.plist") as String
    }

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

        let filePath = self.dataFilePath()

        if (NSFileManager.defaultManager().fileExistsAtPath(filePath)){
            let array = NSArray(contentsOfFile: filePath) as! [String]
            for (var i=0;i<array.count;i++){
                linefields[i].text = array [i]
            }
        }

        let app = UIApplication.sharedApplication()
        NSNotificationCenter.defaultCenter().addObserver(self,selector: "applicationWillResignActive:",name:UIApplicationWillResignActiveNotification,
            object: app)

    }

    func applicationWillResignActive(notification:NSNotification){
        let filePath = self.dataFilePath()
        let array = (self.linefields as NSArray).valueForKey("text") as! NSArray
         //-----> Next line: fatal error: unexpectedly found nil while unwrapping an Optional value
        array.writeToFile(filePath, atomically:true)
    }

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

Does anyone know about this?

enter image description here

Upvotes: 2

Views: 764

Answers (2)

Nirupa
Nirupa

Reputation: 787

Check your connections from textFeilds (storyboard file ) to Outlets(swift file). Because missing connections would return nil.

Upvotes: 3

owlswipe
owlswipe

Reputation: 19469

This is swift's error for when you tell it there will be a value in a certain variable, but there was not one. Basically, one of the variables you were reading data from had no data, because for some reason it had never been assigned data.

As commenters have recently said, it is probably this line: (self.linefields as NSArray).valueForKey("text") as! NSArray. My advice is to switch the as! to as? or as, because this won't tell swift, "there is definitely a value here." Other comments have suggested trying to substitute this potential problem line with something simpler and use the map() function more carefully elsewhere in your code.

Upvotes: 0

Related Questions