Reputation: 6707
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?
Upvotes: 6
Views: 1956
Reputation: 42449
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)
}
Upvotes: 10