有没有一种编码和解码闭包的方法? [英] Is there a way to encode and decode the closures?

查看:80
本文介绍了有没有一种编码和解码闭包的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于某种原因,我需要序列化一个包含多个闭包字段的类对象.

For some reason, I need to serialize a class object that contains several closure fields.

赞:

import Foundation

class Foo: NSObject, NSCoding {

    var bar: (() -> Void)

    override init() {
        bar = {}
    }

    required init(coder aDecoder: NSCoder) {
        bar = aDecoder.decodeObject(forKey: "bar") as! (() -> Void)
    }

    func encode(with aCoder: NSCoder) {
        aCoder.encode(bar, forKey: "bar")
    }

}

let foo = Foo()
foo.bar = {
    print("Help!")
}

let data = NSKeyedArchiver.archivedData(withRootObject: foo)
let object = NSKeyedUnarchiver.unarchiveObject(with: data) as! Foo

有什么办法可以得到我想要的东西吗?

Is there any way I can get what I want?

推荐答案

闭包是不可编译的,因为它们是编译到程序中的块代码.除了它们可能需要动态捕获程序状态的一部分(这导致完成这项工作面临技术难题)这一事实之外,还要考虑允许您随意编码和解码可执行部分的安全性问题.程序:当您尝试将编码的类重新加载回您的应用程序并运行它时,会发生什么?如果有人恶意编辑了存档以将代码插入您的程序怎么办?没有可靠的方法可以判断闭包是否有效/安全,然后再将其加载回您的进程中.

Closures are not encodable or decodable as they are blocks code compiled into your program. Besides the fact that they might need to capture parts of the state of your program dynamically (which leads to a difficult technical challenge of making this work), consider the security implications of allowing you to arbitrarily encode and decode parts of the executable portions of your program: what happens when you attempt to reload the encoded class back into your app and run it? What if someone has maliciously edited an archive to insert code into your program? There is no reasonable way to tell whether the closure is valid/safe to run or not, past loading it back into your process.

这将是非常不安全的,并且通常甚至是系统不允许的. (也许是针对可写内存与可执行内存进行比较.出于安全考虑,许多操作系统将内存块指定为 是可执行的(例如程序中的代码)是可写的[例如,您读入内存/进行操作的数据],但不能同时使用两者.)

This would be terribly insecure, and is generally not even allowed by the system. (Perhaps look into writable vs. executable memory — for this security reason, many operating systems designate blocks of memory as either being executable [e.g. the code in your program] or writable [e.g. data that you read into memory/manipulate], but not both.)

这篇关于有没有一种编码和解码闭包的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆