Swift - 尝试使用NSUserDeafults

时间:2016-02-15 20:38:17

标签: ios swift2 xcode7

我正在关注使用Swift 2和Xcode 7中的NSUserDefault保存和检索数据的教程。但是我在控制台中收到此错误:

  

致命错误:在解包可选值时意外发现nil

我查了几篇帖子: 1 .- How to save an array of objects to NSUserDefault with swift? 2.- (Swift) Storing and retrieving Array to NSUserDefaults 我认为根据这些帖子代码是可以的,但错误就在那里。这是我的控制台http://screencast.com/t/DnilCnom的屏幕截图 当我尝试在ViewController中的蓝色函数中打印peopleArray时出现错误。 这是我的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)

                }
            }
        }
    }
}

这是我的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")
    }
}

有什么想法吗?

0 个答案:

没有答案