ios本地存储(swift版)查看真机沙盒 归解档 本地数据持久化

1.Document

1.1 写入数据到本地

var currentMdict = NSMutableDictionary();//UUID name version bytes
let filePath:String = NSHomeDirectory() + "/Documents/my.plist";
currentMdict.addEntries(from: ["version":version,"bytes":saveLocalBytes()]);
currentMdict.addEntries(from: ["UUID":cameraPhoneNum,"name":"camera"]);
    let arr = NSMutableArray();
    arr.add(currentMdict);
    arr.write(toFile: filePath, atomically: true);

func saveLocalBytes() -> [UInt8] {}

1.2 从本地取出数据

 let filePath:String = NSHomeDirectory() + "/Documents/my.plist";
 let getArr = NSArray(contentsOfFile: filePath);
 if getArr?.count ?? 0 > 0{
               homeVC.cameraList = getArr as! Array<[String : Any]>;
        }

1.3另一个存数据的例子

let arr1 = NSMutableArray(array: [1,2,3,"shen"])
let filePath1:String = NSHomeDirectory() + "/Documents/my1.plist";
arr1.write(toFile: filePath1, atomically: true)
print(filePath1)

打印结果:/var/mobile/Containers/Data/Application/94EECE1F-B41C-4D89-BC16-88D4FCAB3134/Documents/my1.plist

1.3.1 上面代码执行后查看真机的沙盒

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

2.归解档(应该也可以直接把对象转成json字符串来存对象,而且应该是更优的做法,下面有相关博客的链接)

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

import UIKit

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)
    }
}

归档:

	var points = [BMKMapPoint]()  //30个元素
    let pathArr = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
    var path: String = pathArr.first!
    path += "/my2.plist"
    var pointArr = [Data]()
    for item in points {
        let pointModel = BMKMapPointModel(point: item)
        let data = try NSKeyedArchiver.archivedData(withRootObject: pointModel)
        pointArr.append(data)
    }
    let pointArrs = NSMutableArray(array: pointArr)
    pointArrs.write(toFile: path, atomically: true)

打断点后 po pathArr:
▿ 1 element
- 0 : “/var/mobile/Containers/Data/Application/7A30D24B-6F54-41F4-AEF2-0A7BDAFF8336/Documents”

上面代码后查看归档后的沙盒

在这里插入图片描述

2.1 复杂一点的归解档示例

这篇博客是接近终极版:
接近终极版

//
//  routeModel.swift
//  CycleBike
//
//  Created by macvivi on 2020/11/23.
//  Copyright © 2020 macvivi. All rights reserved.
//




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! RouteModel.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 {
    let shareInstance = MyFileManager()
    
    static var routesPath: String {
        var pathFile = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).first!
        pathFile += "/routes.plist"
        return pathFile
    }
    
    //解档
    static var getRouteModelArr: [RouteModel] {
        var routeModelArr = [RouteModel]()
        let dataArr =  NSArray.init(contentsOfFile: MyFileManager.routesPath)
        for i in 0..<dataArr!.count {
            let routeModel: RouteModel = NSKeyedUnarchiver.unarchiveObject(with: dataArr![i] as! Data) as! RouteModel
            routeModelArr.append(routeModel)
        }
        return routeModelArr
    }
    
    
}

归档:

                let name: String = startStr! + NSLocalizedString("to", comment: "") + destinationStr!
                let routeModel = RouteModel(name: name, points: points, typeID: "未上传")
                let data = NSKeyedArchiver.archivedData(withRootObject: routeModel)
                let routesArr = NSMutableArray()
                routesArr.add(data)
                routesArr.write(toFile: MyFileManager.routesPath, atomically: true)

归档后的沙盒
在这里插入图片描述
解档后的断点截图
在这里插入图片描述
参考博客:
iOS开发 查看真机沙盒文件
Swift4.2如何优雅的使用归档解档(该博客中遵守codable协议的方法无用)
swift 归档和解档 - 简书

3.UserDefaults(NSUserDefaults)

class MyFileManager {
    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
        }
    }
    
}

参考博客:

ios本地存储的五种方式
iOS基础–沙盒-数据本地化-归解档-整理总结(1)
iOS开发中的4种数据持久化方式【一、属性列表与归档解档

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