如何将自定义对象的数组列表存储到NSUserDefaults?

时间:2015-03-23 16:51:40

标签: ios swift

class Item
{
    var name: String
    var collectionId: Int

    init(name: String, collectionId: Int) {
        self.name = name
        self.collectionId = collectionId

    }
}

class ViewController:UIViewController
{
    var itemList = [Item]()

    func recievedResults()
    {
        let defaults = NSUserDefaults.standardUserDefaults()
        defaults.setObject(self.itemList, forKey: "myList")
    }        
}

我收到错误"属性列表不能包含' CFType'"

类型的对象

如何将itemList存储到NSUserDefaults?

4 个答案:

答案 0 :(得分:5)

首先,你必须从NSObject继承Item,使用coder&解码器方法:

class Item :NSObject
{
    var name: String = ""
    var collectionId: Int = 0

    init(name: String, collectionId: Int) {
        self.name = name
        self.collectionId = collectionId
    }

    init(coder decoder: NSCoder) {
        self.name = decoder.decodeObjectForKey("name") as String
        self.collectionId = decoder.decodeIntegerForKey("collectionId")
    }

    func encodeWithCoder(coder: NSCoder) {
        coder.encodeObject(self.name, forKey: "name")
        coder.encodeInt(Int32(self.collectionId), forKey: "collectionId")
    }
}

然后,这些是插入&的功能。从NSUserDefaults检索。

func insertItems()
    {
        let defaults = NSUserDefaults.standardUserDefaults()

        let data = NSKeyedArchiver.archivedDataWithRootObject(itemList)
        NSUserDefaults.standardUserDefaults().setObject(data, forKey: "myList")
    }

func retrieveItems()
{
    let defaults = NSUserDefaults.standardUserDefaults()

    if let data = NSUserDefaults.standardUserDefaults().objectForKey("myList") as? NSData {
        let _mySavedList = NSKeyedUnarchiver.unarchiveObjectWithData(data) as [Item]
    }
}

示例:

let item1 = Item(name: "Item 1", collectionId: 1)
let item2 = Item(name: "Item 2", collectionId: 2)

itemList.append(item1)
itemList.append(item2)


insertItems()
retrieveItems()

答案 1 :(得分:2)

您需要为自定义类实现协议NSCoding。请参阅此Swift example

答案 2 :(得分:2)

Swift 4 起,使用Codable更加简单:

import Foundation

//Declaration
struct Item: Codable {
    var name: String
    var collectionId: Int
}

//Initialization
let itemA: Item = Item.init(name: "Bob A.", collectionId: 1)
let itemB: Item = Item.init(name: "Bob B.", collectionId: 1)
let items: [Item] = [itemA, itemB]

//Storing Items
if let encoded = try? JSONEncoder().encode(items) {
    UserDefaults.standard.set(encoded, forKey: "items")
}

//Retrieving Items
do {
    let storedObjItem = UserDefaults.standard.object(forKey: "items")
    let storedItems = try JSONDecoder().decode([Item].self, from: storedObjItem as! Data)
    print("Retrieved items: \(storedItems)")
} catch let err {
    print(err)
}

答案 3 :(得分:1)

正如this堆栈溢出问题所指出的,您无法在NSUserDefaults中存储自定义对象。

但是你可以使你的NSCoding类符合并存储来自NSKeyedArchiver.archivedDataWithRootObject(...)的NSData:

class Item : NSObject, NSCoding {
    var name: String
    var collectionId: Int

    init(name: String, collectionId: Int) {
        self.name = name
        self.collectionId = collectionId
    }

    required init(coder aDecoder: NSCoder) {
        collectionId = aDecoder.decodeIntegerForKey("collectionId")
        name = aDecoder.decodeObjectForKey("name") as String
    }

    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeInteger(collectionId, forKey: "collectionId")
    }
}

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        recievedResults()
    }

    var itemList = [Item]()

    func recievedResults()
    {
        self.itemList.append(Item(name: "test", collectionId: 2))

        let defaults = NSUserDefaults.standardUserDefaults()
        defaults.setObject(NSKeyedArchiver.archivedDataWithRootObject(itemList), forKey: "myList")

        let data = defaults.objectForKey("myList") as NSData
        if let decodedList = NSKeyedUnarchiver.unarchiveObjectWithData(data) as? [Item]{
            print("first item: \(decodedList)")
        }
    }
}