Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catching NSKeyedUnarchiver exception

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?

like image 272
JP Hribovsek Avatar asked Oct 15 '14 03:10

JP Hribovsek


1 Answers

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)
}
like image 92
JAL Avatar answered Sep 22 '22 06:09

JAL