在UserDefaults中存储多个数组

时间:2018-12-03 00:59:45

标签: swift nsuserdefaults

想知道是否可以在iOS UserDefaults存储中存储阵列。我有一个带有不同配置文件的屏幕,该屏幕将在订购过程中用作预定义的输入。没有用户登录系统,因此我打算为此使用UserDefaults模块,而不是在线数据库存储。

所需数组:

[
  "Profile 1" : ["title" : "Ing.",
                 "salutation" : "Herr",
                 "fullname" : "Franz Bernstein Stiglitz"
                 "phone" : "13001300",
                 "email" : "john2doe@example.com",
                ],
  "Profile 2" : ["title" : "Dr.",
                 "salutation" : "Herr",
                 "fullname" : "Joseph Keusch"
                 "phone" : "06606666800",
                 "email" : "jkeusch_1974@example.com",
                ],
]

enter image description here

我有这个带有Model的Struct,使用它我可以将其存储为单个KVS(没有“数组逻辑”)。

struct OrderingProfiles {

    static let (titleKey, salutationKey, fullnameKey, phoneKey, emailKey) = ("title", "salutation", "fullname", "phone", "email")
    static let userSessionKey = "com.save.usersession"

    struct OrderingProfile {
        var title: String?
        var salutation: String?
        var fullname: String?
        var phone: String?
        var email: String?

        init(_ json: [String: String]) {
            self.title = json[titleKey]
            self.salutation = json[salutationKey]
            self.fullname = json[fullnameKey]
            self.phone = json[phoneKey]
            self.email = json[emailKey]
        }
    }

    static var saveOrderingProfile = { (title: String, salutation: String, fullname: String, phone: String, email: String) in
        UserDefaults.standard.set([titleKey: title, salutationKey: salutation, fullnameKey: fullname, phoneKey: phone, emailKey: email], forKey: userSessionKey)
    }

    static var getOrderingProfile = { _ -> OrderingProfile in
        return OrderingProfile((UserDefaults.standard.value(forKey: userSessionKey) as? [String: String]) ?? [:])
    }(())

    static func clearUserData(){
        UserDefaults.standard.removeObject(forKey: userSessionKey)
    }

}

1 个答案:

答案 0 :(得分:-1)

如果您的回复是这样

[
      "Profile" : ["title" : "Ing.",
                     "salutation" : "Herr",
                     "fullname" : "Franz Bernstein Stiglitz"
                     "phone" : "13001300",
                     "email" : "john2doe@example.com",
                    ],
      "Profile" : ["title" : "Dr.",
                     "salutation" : "Herr",
                     "fullname" : "Joseph Keusch"
                     "phone" : "06606666800",
                     "email" : "jkeusch_1974@example.com",
                    ],
    ]

使用第三方模型映射尝试此代码
库链接:-https://github.com/tristanhimmelman/ObjectMapper

1)模型类别

import UIKit
import ObjectMapper
class ProfileModel:NSObject , Mappable , NSCoding {
    var Profile:[ProfileData]?


    required init?(map: Map) {

    }
     required init(coder aDecoder: NSCoder) {
        self.Profile =  aDecoder.decodeObject(forKey:"Profile") as? [ProfileData]
    }
    public func encode(with aCoder: NSCoder) {

        aCoder.encode(Profile, forKey: "Profile")
    }
    func mapping(map: Map) {

        Profile           <- map["Profile"]
    }
}

class ProfileData:NSObject , Mappable , NSCoding {


    var title:String?
    var salutation:String?
    var fullname:String?
    var phone:String?
    var fullname:String?



    required init?(map: Map) {

    }


    //==========================================
    //MARK: - NSCoder Initializer Methods
    //==========================================


    required init(coder aDecoder: NSCoder) {

        self.title = aDecoder.decodeObject(forKey: "title") as? String
        self.salutation =  aDecoder.decodeObject(forKey:"salutation") as? String
        self.fullname =  aDecoder.decodeObject(forKey:"fullname") as? String
        self.phone =  aDecoder.decodeObject(forKey:"phone") as? String
        self.email =  aDecoder.decodeObject(forKey:"email") as? String



    }


    public func encode(with aCoder: NSCoder) {

        aCoder.encode(title, forKey: "title")
        aCoder.encode(salutation, forKey: "salutation")
        aCoder.encode(fullname, forKey: "fullname")
        aCoder.encode(phone, forKey: "phone")
        aCoder.encode(email, forKey: "email")


    }


    //==========================================
    //MARK: - Mappable Protocol Methods
    //==========================================


    func mapping(map: Map) {

        title           <- map["title"]
        salutation      <- map["salutation"]
        fullname        <- map["fullname"]
        phone           <- map["phone"]
        email           <- map["email"]

    }



}

在UserDefaults中保存数据

1)保存数据代码

var arrayProfile:[ProfileData] = []
var arrprofile:[ProfileModel] = []
let defaults = UserDefaults.standard

for data in arrprofile
{
 arrayProfile.append(data)
}

let saveProfileData = NSKeyedArchiver.archivedData(withRootObject: arrayProfile)
defaults.set(saveProfileData, forKey: "profile")
defaults.synchronize()

2)检索数据

var arrayProfile:[ProfileData] = []
let defaults = UserDefaults.standard
 guard let profile_data = defaults.object(forKey: "profile") as? NSData else {
            print("'profile' not found in UserDefaults")
                            return
        }
        guard let placesArray = NSKeyedUnarchiver.unarchiveObject(with: profile_data as Data) as? [ProfileData] else {
                            print("Could not unarchive from profile_data")
                            return
                        }

        for place in placesArray
        {
            arrayProfile.append(place)

        }

在我的情况下,可以100%尝试一下