在NSUserDefaults中保存自定义NSObject

时间:2016-03-22 05:48:48

标签: ios swift nsuserdefaults nsobject nskeyedarchiver

我有一个模态实体文件,如下所示,

import UIKit
class MyProfile: NSObject {
   var userName : String = ""

    func initWithDict(dict: NSMutableDictionary) {
     self.userName =  dict.objectForKey("username") as! String
    }
}

按以下编码保存该实体,

    let myDict: NSMutableDictionary = ["username": "abc"]
    let myEntity:MyProfile = MyProfile()
    myEntity.initWithDict(myDict)
    let userDefaults = NSUserDefaults.standardUserDefaults()
    let encodedData = NSKeyedArchiver.archivedDataWithRootObject(myEntity)
    userDefaults.setObject(encodedData, forKey: "MyProfileEntity")
    userDefaults.synchronize()

获取下面保存的实体,

    let myEntity:MyProfile = MyProfile()
    let userDefaults = NSUserDefaults.standardUserDefaults()
    guard let decodedNSData = userDefaults.objectForKey("MyProfileEntity") as? NSData,
        myEntity = NSKeyedUnarchiver.unarchiveObjectWithData(decodedNSData) as? MyProfile!
        else {
            print("Failed")
            return
    }

    print(myEntity.userName)

它没有工作,崩溃和语法错误很多,我是swift的新手,

它在unarchiveObjectWithData行中显示了一些语法错误,例如定义与之前的值冲突。如果我修复了这个错误,那么在从userdefaults获取实体时它就会崩溃。

任何人都可以建议我如何解决它?

2 个答案:

答案 0 :(得分:2)

要将自定义对象保存为用户默认值,必须实现NSCoding协议。请替换您的自定义数据模型:

class MyProfile: NSObject,NSCoding {
var userName : String = ""

@objc required init(coder aDecoder:NSCoder){

    self.userName = aDecoder.decodeObjectForKey("USER_NAME") as! String

}

@objc func encodeWithCoder(aCoder: NSCoder) {
  aCoder.encodeObject(self.userName, forKey: "USER_NAME")
}

init(dict: [String: String]) {

    self.userName = dict["username"]!
}

override init() {
    super.init()
}

}

以下是保存和检索MyProfile对象的代码:

// Save profile
    func saveProfile(profile: MyProfile){
        let filename = NSHomeDirectory().stringByAppendingString("/Documents/profile.bin")
        let data = NSKeyedArchiver.archivedDataWithRootObject(profile)
        data.writeToFile(filename, atomically: true)
    }
    // Get profile
    func getProfile() -> MyProfile?{

        if let data = NSData(contentsOfFile: NSHomeDirectory().stringByAppendingString("/Documents/profile.bin")){

            let unarchiveProfile = NSKeyedUnarchiver.unarchiveObjectWithData(data) as! MyProfile

                return unarchiveProfile

        } else{

            return nil

        }

    }

现在这里是代码片段如何使用这些方法:

// Create profile object
let profile = MyProfile(dict: ["username" : "MOHAMMAD"])
// save  profile
saveProfile(profile)

// retrieve profile
if let myProfile = getProfile(){
    print(myProfile.userName)
}else{
    print("Profile not found")
}

答案 1 :(得分:1)

你不能这样做:

let myEntity:MyProfile = MyProfile()

然后,请执行此操作:

myEntity = ...

当使用' let'定义某些内容时,您无法更改它。

更改为     var myEntity:MyProfile?

有可能

NSKeyedUnarchiver.unarchiveObjectWithData(decodedNSData)

返回零。然后,您可以通过添加

来强制解包
as? MyProfile!

尝试将此更改为

as? MyProfile

然后,看看你有什么回来

if let myEntity = myEntity {
    print(myEntity.userName)
}