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")
}
}
I get an error "property lists cannot contain objects of type 'CFType'"
How do I store and get the itemList to NSUserDefaults?
Since Swift 4 it is so much more easy using 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)
}
First, you have to inherit Item from NSObject, with coder & decoder methods:
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")
}
}
Then, these are functions to insert & retrieve from 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]
}
}
Example:
let item1 = Item(name: "Item 1", collectionId: 1)
let item2 = Item(name: "Item 2", collectionId: 2)
itemList.append(item1)
itemList.append(item2)
insertItems()
retrieveItems()
You need to implement protocol NSCoding for your custom class. Please see this Swift example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With