简体   繁体   English

编码复杂对象swift 3.0

[英]Encode complex object swift 3.0

I already read several posts and tried every solution, nothing works in my case. 我已经阅读了几篇文章,并尝试了每种解决方案,但对我而言没有任何作用。

I am using this complex data structure and need to store array of DrawnObjects in file. 我正在使用这种复杂的数据结构,并且需要在文件中存储绘制对象数组。 But it crashing when it first came to encode a variable which itself is an array of Structure type. 但是,当它第一次编码一个本身就是结构类型数组的变量时,它就会崩溃。 Any help ? 有什么帮助吗?

[_SwiftValue encodeWithCoder:]: unrecognized selector sent to instance 0x1702668c0 [_SwiftValue encodeWithCoder:]:无法识别的选择器已发送到实例0x1702668c0

enum ArchiverKeys : String
{
    case imageView = "ImageView"
    case stateArray = "StateArray"
    case bezierPathArray = "BezierPathArray"
    case reactangleArray = "ReactangleArray"
    case deleted = "Deleted"
}
   struct RectanglePath {
        var point1: CGPoint
        var point2: CGPoint
        var point3: CGPoint
        var point4: CGPoint
    }

    struct StateObject {
        var isAdd = true
        var path  = String()
    }

    class DrawObject: NSObject , NSCoding {

        var ImageView = UIImageView()
        var arrStates = [StateObject]()
        var arrBezierPaths = [UIBezierPath]()
        var rects = [RectanglePath]()
        var deleted = false


        override init() {
            ImageView = UIImageView()
            arrStates = []
            arrBezierPaths = []
            rects = []
            deleted = false
        }

        func encode(with archiver: NSCoder) {
            archiver.encode(self.ImageView, forKey:ArchiverKeys.imageView.rawValue )
            archiver.encode(self.arrStates, forKey: ArchiverKeys.stateArray.rawValue)
            archiver.encode(self.arrBezierPaths, forKey:ArchiverKeys.bezierPathArray.rawValue )
            archiver.encode(self.rects, forKey: ArchiverKeys.reactangleArray.rawValue)
            archiver.encode(self.deleted, forKey: ArchiverKeys.deleted.rawValue)
        }

        required convenience init(coder unarchiver: NSCoder) {

            self.init()

            self.ImageView      = unarchiver.decodeObject(forKey: ArchiverKeys.imageView.rawValue) as! UIImageView
            self.arrStates      = unarchiver.decodeObject(forKey: ArchiverKeys.stateArray.rawValue) as! [StateObject]
            self.arrBezierPaths = unarchiver.decodeObject(forKey: ArchiverKeys.bezierPathArray.rawValue) as! [UIBezierPath]
            self.rects          = unarchiver.decodeObject(forKey: ArchiverKeys.reactangleArray.rawValue) as! [RectanglePath]
            self.deleted        = (unarchiver.decodeObject(forKey: ArchiverKeys.deleted.rawValue) != nil)
        }
    }

    func saveArrayTo(_ directoryName: String , arrayToSave: NSArray) {

     //   let encodedData = NSKeyedArchiver.archivedData(withRootObject: arrayToSave)
      NSKeyedArchiver.archiveRootObject(arrayToSave, toFile: directoryName)
    }

     func loadArrayFrom(_ directoryName: String ) -> NSArray? {
        let result = NSKeyedUnarchiver.unarchiveObject(withFile: directoryName)
        return result as? NSArray
    }

You cannot encode a Swift struct out of the box, you have to add a computed property and an init method to make the struct property list compliant 您不能开箱即用地对Swift结构进行编码,必须添加一个计算属性和一个init方法以使该结构属性列表兼容

struct StateObject {
    var isAdd = true
    var path  = ""

    init(propertyList : [String:Any]) {
        self.isAdd = propertyList["isAdd"] as! Bool
        self.path = propertyList["path"] as! String
    }

    var propertyListRepresentation : [String:Any] {
        return ["isAdd" : isAdd, "path"  : path]
    }
}

Now you can archive the array 现在您可以存档阵列

archiver.encode(self.arrStates.map{$0.propertyListRepresentation}, forKey: ArchiverKeys.stateArray.rawValue)

and unarchive it 并取消存档

let states = unarchiver.decodeObject(forKey: ArchiverKeys.stateArray.rawValue) as! [[String:Any]]
self.arrStates = states.map { StateObject(propertyList: $0) }

Alternatively leave StateObject unchanged and 或者,保持StateObject不变,并

  • in encode(with replace the line encode(with替换行

     archiver.encode(self.arrStates, forKey: ArchiverKeys.stateArray.rawValue) 

    with

     let arrStatesAsPlist = arrStates.map { return ["isAdd" : $0.isAdd, "path" : $0.path] } archiver.encode(arrStatesAsPlist, forKey:ArchiverKeys.stateArray.rawValue) 
  • in init(coder replace the line init(coder替换行

     archiver.encode(self.arrStates, forKey: ArchiverKeys.stateArray.rawValue) 

    with

     let arrStatesAsPlist = unarchiver.decodeObject(forKey: ArchiverKeys.stateArray.rawValue) as! [[String:Any]] arrStates = arrStatesAsPlist.map { StateObject(isAdd: $0["isAdd"] as! Bool, path: $0["path"] as! String) } 

Notes: 笔记:

  • Since you are assigning default values to all properties you can delete the entire init() method and the init() call in init(coder . 由于您正在为所有属性分配默认值,因此可以删除整个init()方法和init(coder init()init()调用。

  • Don't use NSArray in Swift. 不要在Swift中使用NSArray Use a native Array 使用本机Array

  • It's not a good idea to archive an UI element like UIImageView . 归档UIImageView这样的UI元素不是一个好主意。 Archive the image data. 存档图像数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM