Converting Swift Array to NSData for NSUserDefaults.StandardUserDefaults persistent storage

后端 未结 2 1780
不思量自难忘°
不思量自难忘° 2021-01-07 05:11

I\'m trying to get my head around Swift (after being relatively competent with Obj-C) by making a small app. I would like to use NSUserDefaults to persistently save a small

2条回答
  •  心在旅途
    2021-01-07 05:52

    Anything you are archiving to NSData and back needs to implement the NSCoding protocol. I found that in addition, my Swift class had to extend NSObject. Here is a quick example of a Swift class that encodes and decodes:

    class B : NSObject, NSCoding {
        var str : String = "test"
    
        required init(coder aDecoder: NSCoder) {
            str = aDecoder.decodeObjectForKey("str") as String
        }
    
        override init() {
        }
    
        func encodeWithCoder(aCoder: NSCoder) {
            aCoder.encodeObject(str, forKey: "str")
        }
    }
    
    // create an Object of Class B
    var b : B = B()
    
    // Archive it to NSData
    var data : NSData = NSKeyedArchiver.archivedDataWithRootObject(b)
    
    // Create a new object of Class B from the data
    var b2 : B = NSKeyedUnarchiver.unarchiveObjectWithData(data) as B
    

提交回复
热议问题