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

HandyJSON - github

1.模型类

import HandyJSON

 class RouteModelJSON: HandyJSON {
    
    class PointModelJSON: HandyJSON {
        required init(){}
        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)
        }
    }
    
    required init(){}
    
    var name: String = ""
    var typeID: String = ""
    var distance: String = ""
    private var points: [PointModelJSON] = []
    var mapPoints: [BMKMapPoint] {
        set {
            for item in newValue {
                self.points.append(PointModelJSON(point: item))
            }
        }
        get {
            var mapPoints = [BMKMapPoint]()
            for item in points {
                mapPoints.append(item.mapPoint)
            }
            return mapPoints
        }
    }
    
    init(name: String, points: [BMKMapPoint], typeID: String) {
        self.name = name
        self.distance = self.distanceStrFromMapPoints(points: points)
        self.typeID = typeID
        self.mapPoints = points
    }

    
//    func mapping(mapper: HelpingMapper) {
//        mapper <<<
//            self.typeID <-- "id"
//    }
}

extension RouteModelJSON {
     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
    }
}

2.本地存取类

class MyFileJSONManager {
    static let shared = MyFileJSONManager()
    
    private var routesPath: String {
        var pathFile = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).first!
        pathFile += "/routes.plist"
        return pathFile
    }
    
    private var JSONStrArr: [String] {
        if let arr = NSArray.init(contentsOfFile: routesPath) {
            return NSArray.init(contentsOfFile: routesPath) as! [String]
        }
        return []
    }
    
    var routeModelArr: [RouteModelJSON] {
        var routeModelArr = [RouteModelJSON]()
        for i in 0..<JSONStrArr.count {
            let routeModel: RouteModelJSON = RouteModelJSON.deserialize(from: JSONStrArr[i])!
            routeModelArr.append(routeModel)
        }
        return routeModelArr
    }
    
    func saveRouteModel(routeModel: RouteModelJSON) {
        let str = routeModel.toJSONString()
        let routesArr = NSMutableArray(array: JSONStrArr)
        routesArr.insert(str, 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
        }
    }

}

3.存

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

4.取

    func loadData() {
        routeModelArr = MyFileJSONManager.shared.routeModelArr
    }
    @IBAction func rightBarBtnItemClick(_ sender: Any) {
        if let routeModel = routeModel {
            self.selectRouteClosure!(routeModel)
        }
        self.dismiss(animated: true, completion: nil)
    }
    vc.selectRouteClosure = { routeModel in
        let points = routeModel.mapPoints
        self.startCoordinate = BMKCoordinateForMapPoint(points.first!)
        self.destinationCoordinate = BMKCoordinateForMapPoint(points.last!)
        self.startEndRoutePaint(points)
    }
    self.present(vc, animated: true, completion: nil)

5.另一个简单模型类实例


import UIKit

import HandyJSON

class EquipmentModel: HandyJSON {
    required init() {}
    
    var name: String = ""
    private var uuidStr: String = ""
    var uuid: UUID {
        set {
            uuidStr = newValue.uuidString
        }
        get {
            UUID(uuidString: uuidStr)!
        }
    }
    init(name: String, uuid: UUID) {
        self.name = name
        self.uuid = uuid
    }

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