ios swift 归解档

0.用字典转模型的框架,将对象转成json字符串后进行本地存储更加简单,推荐使用

iOS 字典转模型纯swift框架HandyJSON使用实例:本地存取

1.归解档类

class RouteModel: NSObject, NSCoding{
    @objc(objc_BMKMapPointModel) class BMKMapPointModel: NSObject, NSCoding{
         func encode(with coder: NSCoder) {
             coder.encode(x, forKey: "x")
             coder.encode(y, forKey: "y")
         }
         required init?(coder: NSCoder) {
             x = coder.decodeObject(forKey: "x") as! Double
             y = coder.decodeObject(forKey: "y") as! Double
         }
         var x: Double = 0
         var y: Double = 0
         init(point: BMKMapPoint) {
             x = point.x
             y = point.y
         }
         var mapPoint: BMKMapPoint {
             BMKMapPoint(x: x, y: y)
         }
     }
    
    func encode(with coder: NSCoder) {
        coder.encode(name, forKey: "name")
        coder.encode(distance, forKey: "distance")
        coder.encode(typeID, forKey: "typeID")
        coder.encode(dataArr, forKey: "dataArr")
    }
    
    required init?(coder: NSCoder) {
        super.init()
        name = coder.decodeObject(forKey: "name") as! String
        distance = coder.decodeObject(forKey: "distance") as! String
        typeID = coder.decodeObject(forKey: "typeID") as! String
        dataArr = coder.decodeObject(forKey: "dataArr") as! [Data]
    }
    
    var name: String = ""
    var distance: String = ""
    var points: [BMKMapPoint] {
        set {
            for item in newValue {
                let pointModel = BMKMapPointModel(point: item)
                let data = NSKeyedArchiver.archivedData(withRootObject: pointModel)
                dataArr.append(data)
            }
        }
        get {
            var points = [BMKMapPoint]()
            for item in dataArr {
                let pointModel:  BMKMapPointModel = NSKeyedUnarchiver.unarchiveObject(with: item) as! BMKMapPointModel
                points.append(pointModel.mapPoint)
            }
            return points
        }
    }
    var typeID: String = ""
    var dataArr: [Data] = []
    
    init(name: String, points: [BMKMapPoint], typeID: String) {
        super.init()
        self.name = name
        self.distance = self.distanceStrFromMapPoints(points: points)
        self.points = points
        self.typeID = typeID
    }
}

extension RouteModel {
     func distanceStrFromMapPoints(points:[BMKMapPoint]) -> String {
        guard points.count != 0 else {
            return ""
        }
        var totalDistancesRoute: Double = 0
        for i in 1..<points.count {
          let distance = BMKMetersBetweenMapPoints(points[i-1],points[i])
          totalDistancesRoute += distance
        }
        var distanceStr = ""
        if totalDistancesRoute < 1000 {
            distanceStr = "\(Int(totalDistancesRoute.roundTo(places: 1)))m"
        }else {
            let totalDistancesKm:Double = totalDistancesRoute/1000
            distanceStr = "\(totalDistancesKm.roundTo(places: 1))km"
        }
       return distanceStr
    }
}

class MyFileManager {
    static let shared = MyFileManager()
    
    var routesPath: String {
        var pathFile = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).first!
        pathFile += "/routes.plist"
        return pathFile
    }
    
    var dataArr: [Data] {
        NSArray.init(contentsOfFile: routesPath) as! [Data]
    }

    var routeModelArr: [RouteModel] {
        var routeModelArr = [RouteModel]()
        for i in 0..<dataArr.count {
            let routeModel: RouteModel = NSKeyedUnarchiver.unarchiveObject(with: dataArr[i] ) as! RouteModel
            routeModelArr.append(routeModel)
        }
        return routeModelArr
    }
    
    func saveRouteModel(routeModel: RouteModel) {
        let data = NSKeyedArchiver.archivedData(withRootObject: routeModel)
        let routesArr = NSMutableArray(array: dataArr)
        routesArr.insert(data, at: 0)
        routesArr.write(toFile: routesPath, atomically: true)
    }
    
    let userDefault = UserDefaults.standard
    
    var userDefaultIndex: Int {
        set {
            userDefault.setValue(newValue, forKey: "index")
            userDefault.synchronize()
        }
        get {
            let index: Int = userDefault.object(forKey: "index") as! Int
            return index
        }
    }
    
}

2.归档

    let name: String = startStr! + NSLocalizedString("to", comment: "") + destinationStr!
    let routeModel = RouteModel(name: name, points: points, typeID: "未上传")
    MyFileManager.shared.saveRouteModel(routeModel: routeModel)
    startEndRoutePaint(points)

3.解档

    var points: [BMKMapPoint] = routeModel.points
    self.startCoordinate = BMKCoordinateForMapPoint(points.first!)
    self.destinationCoordinate = BMKCoordinateForMapPoint(points.last!)
    self.startEndRoutePaint(points)

4.错误

解档的时候会报下面的错误
在这里插入图片描述

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页