Swift NSKeyedArchiver

前端之家收集整理的这篇文章主要介绍了Swift NSKeyedArchiver前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let filePath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory,NSSearchPathDomainMask.UserDomainMask,true)[0] + "/person.dat"

        //归档
        let data = NSMutableData()
        let archiver = NSKeyedArchiver.init(forWritingWithMutableData: data)
        let array = ["1","2","3"]
        archiver.encodeObject(array,forKey:"arr")
        archiver.encodeInt(20,forKey: "age")
        archiver.finishEncoding()
        data.writeToFile(filePath,atomically: true)

        //反归档
        let unarchiverData = NSData(contentsOfFile: filePath)
        let unarchiver = NSKeyedUnarchiver.init(forReadingWithData: unarchiverData!)
        let decodeData = unarchiver.decodeObjectForKey("arr") as! NSArray
        let decodeAge = unarchiver.decodeIntForKey("age")
        NSLog("%@",decodeData)
        NSLog("%d",decodeAge)
    }
}

1.在带键的归档中,每个归档字段都有一个key值,解归档时key值要与归档时key值匹配 2.带键归档可以一次存储多个对象 3.归档的对象是Foundation框架中的对象 4.归档和解归档其中任意对象都需要归档和解归档整个文件 5.归档后的文件是加密的,所以归档文件的扩展名可以随意取

原文链接:https://www.f2er.com/swift/323256.html

猜你在找的Swift相关文章