Is there a way to encode and decode closures?

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

Like this:

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 a way to get what I want?

+3


source to share


1 answer


The closures are not encoded or decoded, as they constitute the code that is compiled into your program. In addition to the fact that they may need to dynamically track parts of your program's state (which leads to a complex technical challenge to get the job done), consider the security implications of allowing randomly encode and decode parts of executable parts of your program: what happens when you try to reload an encoded class back to your application and run it? What if someone maliciously edited the archive to insert the code into your program? There is no sane way to tell if a closure is valid / safe to start or not, after loading it back into your process.



This would be terribly insecure and not allowed by the system at all. (Perhaps look at writeable and executable memory - for this reason, many operating systems refer to blocks of memory as executable (like code in your program) or writable (like data you read into / manipulate), but not others. )

+3


source







All Articles