Here is an example of reading and writing a list of objects of type SNStock
that implements NSCoding
- we have an accessor for the entire list, watchlist
, and two methods to add and remove objects, that is addStock(stock: SNStock)
and removeStock(stock: SNStock)
.
import Foundation
class DWWatchlistController {
private let kNSUserDefaultsWatchlistKey: String = "dw_watchlist_key"
private let userDefaults: NSUserDefaults
private(set) var watchlist:[SNStock] {
get {
if let watchlistData : AnyObject = userDefaults.objectForKey(kNSUserDefaultsWatchlistKey) {
if let watchlist : AnyObject = NSKeyedUnarchiver.unarchiveObjectWithData(watchlistData as! NSData) {
return watchlist as! [SNStock]
}
}
return []
}
set(watchlist) {
let watchlistData = NSKeyedArchiver.archivedDataWithRootObject(watchlist)
userDefaults.setObject(watchlistData, forKey: kNSUserDefaultsWatchlistKey)
userDefaults.synchronize()
}
}
init() {
userDefaults = NSUserDefaults.standardUserDefaults()
}
func addStock(stock: SNStock) {
var watchlist = self.watchlist
watchlist.append(stock)
self.watchlist = watchlist
}
func removeStock(stock: SNStock) {
var watchlist = self.watchlist
if let index = find(watchlist, stock) {
watchlist.removeAtIndex(index)
self.watchlist = watchlist
}
}
}
Remember that your object needs to implement NSCoding
or else the encoding won't work. Here is what SNStock
looks like:
import Foundation
class SNStock: NSObject, NSCoding
{
let ticker: NSString
let name: NSString
init(ticker: NSString, name: NSString)
{
self.ticker = ticker
self.name = name
}
//MARK: NSCoding
required init(coder aDecoder: NSCoder) {
self.ticker = aDecoder.decodeObjectForKey("ticker") as! NSString
self.name = aDecoder.decodeObjectForKey("name") as! NSString
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(ticker, forKey: "ticker")
aCoder.encodeObject(name, forKey: "name")
}
//MARK: NSObjectProtocol
override func isEqual(object: AnyObject?) -> Bool {
if let object = object as? SNStock {
return self.ticker == object.ticker &&
self.name == object.name
} else {
return false
}
}
override var hash: Int {
return ticker.hashValue
}
}
Hope this helps!