0

I am following a tutorial about save and retrieve data with NSUserDefault in Swift 2 and Xcode 7. But I get this error in console:

fatal error: unexpectedly found nil while unwrapping an Optional value

I checked a couple of post about that: 1.-How to save an array of objects to NSUserDefault with swift? 2.- (Swift) Storing and retrieving Array to NSUserDefaults And I think the code is ok according those post, however the error is on there. This is a screenshot of my console http://screencast.com/t/DnilCnom The error appears when a I try to print peopleArray in the blue function in the ViewController. This is my ViewController:

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var favLbl: UILabel!

    var people = [Person]()
    let defaults = NSUserDefaults.standardUserDefaults()

    override func viewDidLoad() {
        super.viewDidLoad()

        if let color = defaults.valueForKey("color") as? String {
            favLbl.text = "Favorite Color: \(color)"
        } else {
            favLbl.text = "Pick a color!"
        }

        let personA = Person(first: "test1", last: "last1")
        let personB = Person(first: "test2", last: "last2")
        let personC = Person(first: "test3", last: "last3")

        people.append(personA)
        people.append(personB)
        people.append(personC)

        let peopleData = NSKeyedArchiver.archivedDataWithRootObject(people)
        defaults.setObject(peopleData, forKey: "people")
        defaults.synchronize()
    }

    @IBAction func red(sender: AnyObject) {
        favLbl.text = "Favorite Color: Red"
        defaults.setValue("Red", forKey: "color")
        defaults.synchronize()
    }

    @IBAction func yellow(sender: AnyObject) {
        favLbl.text = "Favorite Color: Yellow"
        defaults.setValue("Yellow", forKey: "color")
        defaults.synchronize()
    }

    @IBAction func blue(sender: AnyObject) {
        favLbl.text = "Favorite Color: Blue"
        defaults.setValue("Blue", forKey: "color")
        defaults.synchronize()

        // Fetch Data from NSUserDefault
        if let loadedPeople = defaults.objectForKey("people") as? NSData {
            if let peopleArray = NSKeyedUnarchiver.unarchiveObjectWithData(loadedPeople) as? [Person]
            {
                for person in peopleArray {
                    print(person.firstName)

                }
            }
        }
    }
}

and this is my Person.swift:

import Foundation

class Person: NSObject, NSCoding {
    var firstName: String!
    var lastName: String!

    init(first: String, last: String) {
        firstName = first
        lastName = last
    }

    override init() {

    }

    required convenience init?(coder aDecoder: NSCoder) {
        self.init()
        self.firstName = aDecoder.decodeObjectForKey("firstname") as? String
        self.lastName = aDecoder.decodeObjectForKey("lastname") as? String
    }

    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(self.firstName, forKey: "firstName")
        aCoder.encodeObject(self.lastName, forKey: "lastName")
    }
}

Any idea?

Community
  • 1
  • 1
Jorge Luis Jiménez
  • 1,203
  • 13
  • 20
  • 1
    There are at least typos `firstname` vs. `firstName` and `lastname` vs. `lastName`. And why are you using optionals and a failable initializer in your class? The init method passes non-optionals. – vadian Feb 15 '16 at 20:43
  • oh God, I think I am so tired I've been coding during long time. You're right that is the problem. Thanks @vadian – Jorge Luis Jiménez Feb 15 '16 at 20:46
  • To be honest, I am not sure why the teacher is using optionals and failable initializer. Even I read that it is not a good practice use the synchronize() method but I see it in the code in some posts – Jorge Luis Jiménez Feb 15 '16 at 20:53

0 Answers0