How to save an array of custom struct to NSUserDefault with swift?

前端 未结 3 1354
情歌与酒
情歌与酒 2020-12-17 03:32

I have an custom struct called \'News\' that I want to append into the array to NSUserDefault. But it\'s showing error \"Type \'News\' does not conform to protocol \'AnyObje

3条回答
  •  余生分开走
    2020-12-17 04:22

    WORKING IN SWIFT 3

    Following a similar approach to ahruss, I ended up implementing in the following way:

    struct MyObject {
        var foo : String
        var bar : String?
    }
    
    extension MyObject {
        init?(data: NSData) {
            if let coding = NSKeyedUnarchiver.unarchiveObject(with: data as Data) as? Encoding {
                foo = coding.foo as String
                bar = coding.bar as String?
            } else {
                return nil
            }
        }
    
        func encode() -> NSData {
            return NSKeyedArchiver.archivedData(withRootObject: Encoding(self)) as NSData
        }
    
        private class Encoding: NSObject, NSCoding {
            let foo : NSString
            let bar : NSString?
    
            init(_ myObject: MyObject) {
                foo = myObject.foo
                bar = myObject.bar
            }
    
            @objc required init?(coder aDecoder: NSCoder) {
                if let foo = aDecoder.decodeObject(forKey: "foo") as? NSString {
                    self.foo = foo
                } else {
                    return nil
                }
                bar = aDecoder.decodeObject(forKey: "bar") as? NSString
            }
    
            @objc func encode(with aCoder: NSCoder) {
                aCoder.encode(foo, forKey: "foo")
                aCoder.encode(bar, forKey: "bar")
            }
    
        }
    }
    

    Oh, and to use it just type the following:

    let myObject = MyObject(foo: "foo", bar: "bar")
    UserDefaults.standard.set(myObject.encode(), forKey: "test")
    

    To fetch it,

    let objectData = UserDefaults.standard.object(forKey: "test") as? Data?
    guard let storedObject = objectData else {
        return
    }
    let fetchedObject: MyObject = MyObject(data: storedObject as NSData)
    

提交回复
热议问题