Swift 3保存并从userDefaults

时间:2016-06-23 00:37:48

标签: nscoding swift3 xcode8 ios10

我在Playground使用Swift 3,Xcode 8.0:

import Foundation
class Person: NSObject, NSCoding {
    var name: String
    var age: Int
    init(name: String, age: Int) {
        self.name = name
        self.age = age
    }
    required convenience init(coder aDecoder: NSCoder) {
        let name = aDecoder.decodeObject(forKey: "name") as! String
        let age = aDecoder.decodeObject(forKey: "age") as! Int
        self.init(
            name: name,
            age: age
        )
    }
    func encode(with aCoder: NSCoder) {
        aCoder.encode(name, forKey: "name")
        aCoder.encode(age, forKey: "age")
    }
}

创建Person数组

let newPerson = Person(name: "Joe", age: 10)
var people = [Person]()
people.append(newPerson)

编码数组

let encodedData = NSKeyedArchiver.archivedData(withRootObject: people)
print("encodedData: \(encodedData))")

保存到userDefaults

let userDefaults: UserDefaults = UserDefaults.standard()
userDefaults.set(encodedData, forKey: "people")
userDefaults.synchronize()

检查

print("saved object: \(userDefaults.object(forKey: "people"))")

从userDefaults

转发
if let data = userDefaults.object(forKey: "people") {
    let myPeopleList = NSKeyedUnarchiver.unarchiveObject(with: data as! Data)
    print("myPeopleList: \(myPeopleList)")
}else{
    print("There is an issue")
}

只需检查存档数据

if let myPeopleList = NSKeyedUnarchiver.unarchiveObject(with: encodedData){
   print("myPeopleList: \(myPeopleList)")
}else{
   print("There is an issue")
}

我无法正确地将数据对象保存到userDefaults,此外,底部的检查会产生错误“致命错误:在解包可选值时意外发现nil”。 “检查”行还显示保存的对象为零。这是我对象的NSCoder中的错误吗?

6 个答案:

答案 0 :(得分:88)

Swift 4 Note

您可以再次在Playground中保存/测试您的值

Swift 3

UserDefaults需要在真实项目中进行测试。注意:无需强制同步。如果要在操场中测试编码/解码,可以使用键控归档器将数据保存到文档目录中的plist文件中。您还需要修复课程中的一些问题:

class Person: NSObject, NSCoding {
    let name: String
    let age: Int
    init(name: String, age: Int) {
        self.name = name
        self.age = age
    }
    required init(coder decoder: NSCoder) {
        self.name = decoder.decodeObject(forKey: "name") as? String ?? ""
        self.age = decoder.decodeInteger(forKey: "age")
    }

    func encode(with coder: NSCoder) {
        coder.encode(name, forKey: "name")
        coder.encode(age, forKey: "age")
    }
}

测试:

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        // setting a value for a key
        let newPerson = Person(name: "Joe", age: 10)
        var people = [Person]()
        people.append(newPerson)
        let encodedData = NSKeyedArchiver.archivedData(withRootObject: people)
        UserDefaults.standard.set(encodedData, forKey: "people")

        // retrieving a value for a key
        if let data = UserDefaults.standard.data(forKey: "people"),
            let myPeopleList = NSKeyedUnarchiver.unarchiveObject(with: data) as? [Person] {
            myPeopleList.forEach({print( $0.name, $0.age)})  // Joe 10
        } else {
            print("There is an issue")
        }
    }
}

答案 1 :(得分:49)

FROM 8.0-jre8-alpine
COPY myapp.war /usr/local/tomcat/webapps/myapp.war

Swift 3已经改变了;这不再适用于价值类型。现在正确的语法是:

let age = aDecoder.decodeObject(forKey: "age") as! Int

有各种不同类型的相关解码...()函数:

let age = aDecoder.decodeInteger(forKey: "age")

修改:Full list of all possible decodeXXX functions in Swift 3

编辑:

另一个重要注意事项:如果您之前保存的数据是使用较早版本的Swift编码的,那么必须必须使用decodeObject()解析,然后使用encode(...)对数据进行重新编码如果它是值类型,则无法再使用decodeObject()对其进行解码。因此,Markus Wyss的答案将允许您处理使用Swift版本编码数据的情况:

let myBool = aDecoder.decodeBoolean(forKey: "myStoredBool")
let myFloat = aDecoder.decodeFloat(forKey: "myStoredFloat")

答案 2 :(得分:11)

试试这个:

self.age = aDecoder.decodeObject(forKey: "age") as? Int ?? aDecoder.decodeInteger(forKey: "age")

答案 3 :(得分:2)

在Swift 4中:

您可以使用Codable从Userdefaults中保存和检索自定义对象。如果您经常这样做,则可以添加为扩展名,并按如下所示使用它。

var app = {

// Url/Path to the augmented reality experience you would like to load
arExperienceUrl: "www/index.html",
// The features your augmented reality experience requires, only define the ones you really need
requiredFeatures: [ "image_tracking"],
// Represents the device capability of launching augmented reality experiences with specific features
isDeviceSupported: false,
// Additional startup settings, for now the only setting available is camera_position (back|front)
startupConfiguration:
{
    "camera_position": "back"
},
// Application Constructor
initialize: function() {
    this.bindEvents();
},
// Bind Event Listeners
//
// Bind any events that are required on startup. Common events are:
// 'load', 'deviceready', 'offline', and 'online'.
bindEvents: function() {
    document.addEventListener('deviceready', this.onDeviceReady, false);
},
// deviceready Event Handler
onDeviceReady: function() {
    app.wikitudePlugin = cordova.require("com.wikitude.phonegap.WikitudePlugin.WikitudePlugin");
    app.wikitudePlugin.isDeviceSupported(app.onDeviceSupported, app.onDeviceNotSupported, app.requiredFeatures);
},
// Callback if the device supports all required features
onDeviceSupported: function() {

    app.wikitudePlugin.loadARchitectWorld(
        app.onARExperienceLoadedSuccessful,
        app.onARExperienceLoadError,
        app.arExperienceUrl,
        app.requiredFeatures,
        app.startupConfiguration
    );
},
// Callback if the device does not support all required features
onDeviceNotSupported: function(errorMessage) {
  alert("Device not supported"+ errorMessage);
},
// Callback if your AR experience loaded successful
onARExperienceLoadedSuccessful: function(loadedURL) {
    /* Respond to successful augmented reality experience loading if you need to */
    alert(AR);
},
// Callback if your AR experience did not load successful
onARExperienceLoadError: function(errorMessage) {
    alert(errorMessage);
}
};

app.initialize();

您的课程必须遵循Codable。它只是可编码和可解码协议的一种类型。

extension UserDefaults {

   func save<T:Encodable>(customObject object: T, inKey key: String) {
       let encoder = JSONEncoder()
       if let encoded = try? encoder.encode(object) {
           self.set(encoded, forKey: key)
       }
   }

   func retrieve<T:Decodable>(object type:T.Type, fromKey key: String) -> T? {
       if let data = self.data(forKey: key) {
           let decoder = JSONDecoder()
           if let object = try? decoder.decode(type, from: data) {
               return object
           }else {
               print("Couldnt decode object")
               return nil
           }
       }else {
           print("Couldnt find key")
           return nil
       }
   }

}

用法:

class UpdateProfile: Codable {
  //Your stuffs
}

有关更多编码和解码自定义类型,请通过Apple's documentation进行操作。

答案 4 :(得分:1)

在UserDefaults中保存“自定义对象”的简单示例如下:

您无需借助THE GREAT'CODABLE'编写用于保存/检索对象的样板代码,这就是您摆脱烦人的手动编码/解码的目的 < / p>

因此,如果您已经在使用NSCoding并切换到Codable(可编码+可分解的组合)协议,请从代码中删除以下两种方法

required init(coder decoder: NSCoder) // NOT REQUIRED ANY MORE, DECODABLE TAKES CARE OF IT

func encode(with coder: NSCoder) // NOT REQUIRED ANY MORE, ENCODABLE TAKES CARE OF IT

让我们从Codable的简单性开始吧...

  

创建要存储在UserDefaults中的自定义结构

struct Person : Codable {
    var name:String
}

OR

class Person : Codable {

    var name:String

    init(name:String) {
        self.name = name
    }
}
  

按如下所示在UserDefaults中保存对象

 if let encoded = try? JSONEncoder().encode(Person(name: "Dhaval")) {
     UserDefaults.standard.set(encoded, forKey: "kSavedPerson")
 }
  

从UserDefaults中加载对象,如下所示:

guard let savedPersonData = UserDefaults.standard.object(forKey: "kSavedPerson") as? Data else { return }
guard let savedPerson = try? JSONDecoder().decode(Person.self, from: savedPersonData) else { return }

print("\n Saved person name : \(savedPerson.name)")

就这样...

  

保存/加载过程中很高兴..:)

答案 5 :(得分:1)

在Swift 5中,我将使用属性包装器来简化代码:

/// A type that adds an interface to use the user’s defaults with codable types
///
/// Example:
/// ```
/// @UserDefaultCodable(key: "nameKey", defaultValue: "Root") var name: String
/// ```
/// Adding the attribute @UserDefaultCodable the property works reading and writing from user's defaults
/// with any codable type
///
@propertyWrapper public struct UserDefaultCodable<T: Codable> {
    private let key: String
    private let defaultValue: T

    /// Initialize the key and the default value.
    public init(key: String, defaultValue: T) {
        self.key = key
        self.defaultValue = defaultValue
    }

    public var wrappedValue: T {
        get {
            // Read value from UserDefaults
            guard let data = UserDefaults.standard.object(forKey: key) as? Data else {
                // Return defaultValue when no data in UserDefaults
                return defaultValue
            }

            // Convert data to the desire data type
            let value = try? JSONDecoder().decode(T.self, from: data)
            return value ?? defaultValue
        }
        set {
            // Convert newValue to data
            let data = try? JSONEncoder().encode(newValue)

            // Set value to UserDefaults
            UserDefaults.standard.set(data, forKey: key)
        }
    }
}