NSKeyedUnarchiver exception capture

In Swift, NSKeyedUnarchiver.unarchiveObjectWithData(data) throws an exception if the data cannot be unpacked.

There are some situations where we cannot guarantee that the data is not corrupted, for example, when reading from a file.

I am not aware of the try / catch mechanism in Swift and that I know a method like canUnarchive that will help prevent an exception.

Besides the implementation of try / catch in Obj-C, is there a clean Swift solution in this solution?

+6
source share
1 answer

Since unarchiveObjectWithData() does not exclude throw its exception, there is currently no way to catch it in Swift (starting with a write). The new NSKeyedUnarchiver decodeTopLevelObject() method has NSKeyedUnarchiver added to the iOS 9 SDK, which throws now contains an error. You can catch this with the do , try , catch control flow.

 do { let result = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(NSData(...)) } catch { print(error) } 
+6
source

Source: https://habr.com/ru/post/976756/


All Articles