0

I'm trying to encode some class properties according to the NSCoding protocol:

 func encode(with aCoder: NSCoder){
      // a Date
      aCoder.encode(startDate, forKey: "startDate");
      // a ()->()
      aCoder.encode(handler, forKey: "handler");   //1
      // a Boolean
      aCoder.encode(rightAway, forKey: "rightAway");
 }

I've isolated the problem to be on the line marked with 1. If i comment that line, everything runs okay. If i do run that line as well, i get unrecognized selector. Is there any special care to take when encoding closures? Thanks in advance.

Doe01
  • 13
  • 5

1 Answers1

1

You get unrecognized selector error in both lines because neither Timer nor a Swift closure conform to NSCoding. An object conforming to the protocol must be inherit from NSObject (which a Swift closure doesn't anyway) and implement init(coder and encode(with:)

Why do you want to encode both? A Timer is an complex class and can easily be recreated and a closure is a function which actually does not contain any valuable data.

PS: Remove the trailing semicolons. This is not Objective-C

vadian
  • 274,689
  • 30
  • 353
  • 361
  • Yeah, indeed was not intended (typo). I've edited the original post. I can rebuild the timer, but what about the closure? I have a class that needs to be passed a function to operate and when restored, i would still need that function. How would i go to solve this? – Doe01 Mar 01 '18 at 11:54
  • You can't store a closure... That would require you to store the entire state of the application. What does the closure you are trying to restore do? – Oscar Apeland Mar 01 '18 at 11:59