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?