6

In Swift, NSKeyedUnarchiver.unarchiveObjectWithData(data) will throw an exception if data can't be unarchived.

There are some situations where we have no guarantee if that the data is not corrupted, such as when reading from a file.

I am not aware of a try/catch mechanism in Swift, nor that I know of a method like canUnarchive that would help prevent the exception.

Besides implementing the try/catch in Obj-C, is there a pure Swift solution to this problem?

JAL
  • 41,701
  • 23
  • 172
  • 300
JP Hribovsek
  • 6,707
  • 2
  • 21
  • 26

1 Answers1

10

Because unarchiveObjectWithData() doesn't throw its exception, there is currently no way to catch it in Swift (as of writing). The iOS 9 SDK has added a new NSKeyedUnarchiver method decodeTopLevelObject() which now throws an error. You can catch this with the do, try, catch control flow.

do {
    let result = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(NSData(...))
} catch {
    print(error)
}
JAL
  • 41,701
  • 23
  • 172
  • 300