如何使用NSKeyedArchiver swift

时间:2016-08-24 07:21:31

标签: arrays swift nscoding nskeyedarchiver

我想在swift中使用NSKeyedArchiver将任何类的数组(例如let array = SymptomsModel)类型保存到设备中。

我知道如果SymptomsModel类包含所有具有原始数据类型的变量,如何保存数组,但如果还包含任何其他类的数组作为其属性,则不知道如何保存它

下面我在示例的帮助下解释了我的问题,请仔细阅读并提供解决方案。 我有一个班级

class SymptomsModel: NSObject, NSCoding ,ResponseJSONObjectSerializable   {
            var slug:String?
            var name:String?
            var images:[Sym_images]?
            var videos:[Sym_videos]?

    struct Keys {
            static let Name = "name"
            static let Slug = "slug"
            static let Images = "images"
            static let Videos = "videos"
         }

     required init(json:SwiftyJSON.JSON) {
         self.slug = json["slug"].string
         self.name = json["name"].string

         self.images = [Sym_images]()
         if let imagesJSON = json["images"].array {
                for(imagesJSON) in imagesJSON {
                    if let newImages = Sym_images(json: imagesJSON){
                        self.images?.append(newImages)
                    }
                }

          }

          self.videos = [Sym_videos]()
          if let videosJSONArray = json["videos"].array {

                for(videosJSON) in videosJSONArray {
                    if let newVideos = Sym_videos(json: videosJSON){
                        self.videos?.append(newVideos)
                    }
                }

           }
       }


  init(dictionary: [String : AnyObject]) {
     self.name = dictionary[Keys.Name] as? String
     self.slug = dictionary[Keys.Slug] as? String
     self.images = dictionary[Keys.Images] as? [Sym_acc_images_objects]

     self.videos = dictionary[Keys.Videos] as? [Sym_acc_videos_objects]

   }
func encodeWithCoder(archiver: NSCoder) {
    archiver.encodeObject(name, forKey: Keys.Name)
    archiver.encodeObject(slug, forKey: Keys.Slug)

    archiver.encodeObject(images, forKey: Keys.Images)
    archiver.encodeObject(videos, forKey: Keys.Videos)
}
required init(coder unarchiver: NSCoder) {
    super.init()
    name = unarchiver.decodeObjectForKey(Keys.Name) as? String
    slug = unarchiver.decodeObjectForKey(Keys.Slug) as? String
    self.images =  unarchiver.decodeObjectForKey(Keys.Slug) as? [Sym_acc_images_objects]
    self.videos =  unarchiver.decodeObjectForKey(Keys.Slug) as? [Sym_acc_videos_objects]
   }

和PersistanceManager类以NskeyedArchiver

保存数据
    class PersistenceManager {

    class private func documentsDirectory() -> NSString {
        let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
        let documentDirectory = paths[0] as String
        return documentDirectory
    }

    class func saveNSArray(arrayToSave: NSArray, key: String) {
        print(" saveNSArray key : \(key)")
        let file = documentsDirectory().stringByAppendingPathComponent(key)
        NSKeyedArchiver.archiveRootObject(arrayToSave, toFile: file)

    }

    class func loadNSArray(path: String) -> NSArray? {
        print(" loadNSArray key : \(path)")
        let file = documentsDirectory().stringByAppendingPathComponent(path)
        let result = NSKeyedUnarchiver.unarchiveObjectWithFile(file)
        return result as? NSArray
    }
}

这是我对保存然后再检索数组的意图

class ViewController: UIViewController{
  var ArraySymptom = [SymptomsModel]()

  override func viewDidLoad() {
    super.viewDidLoad()
    ArraySymptom = loadArray()

    //saving data in device
    PersistenceManager.saveNSArray(ArraySymptom, key: "Symptom")


   //loading data from device
       if let value = PersistenceManager.loadNSArray("Symptom") as? [SymptomsModel]  {
            let images = value[0].images
            print("images : \(images)")
            let slug = value[0].slug
            print("slug : \(slug)")
       }              
  }

这里可以获取slug的值,但无法获取图像值。 它可能会发生,因为slug是String类型而Images是Custom Class类型。 请建议我完成它的方式。 是否可以使用NSKeyedArchiver保存这些类型的数组,这样我只需从设备中检索ArraySymptom即可访问图像值。

1 个答案:

答案 0 :(得分:2)

愚蠢的错误

我在图像中变为零,因为它是用错误的密钥解码的,这是复制粘贴错误

错误就在这个函数中..

required init(coder unarchiver: NSCoder) {
super.init()
name = unarchiver.decodeObjectForKey(Keys.Name) as? String
slug = unarchiver.decodeObjectForKey(Keys.Slug) as? String
self.images =  unarchiver.decodeObjectForKey(Keys.Slug) as? [Sym_images]
self.videos =  unarchiver.decodeObjectForKey(Keys.Slug) as? [Sym_videos]

}

正确的解码必须是

  

self.images = unarchiver.decodeObjectForKey( Keys.Images )为?   [Sym_images]

     

self.videos = unarchiver.decodeObjectForKey( Keys.Videos )为?   [Sym_videos]