I am trying to set the value of an @objc
object in my Swift code using obj.setValue(value, forKey: key)
.
It works fine when the object has the property being set. But if it doesn't, my app crashes hard with an uncaught NSException
("class is not key value coding-compliant…").
How can I catch and absorb this exception like I can in Objective-C so as to not crash my app? I tried wrapping it in a Swift try-catch, but it complains that none of the instructions throws and does nothing.
An object that represents a special condition that interrupts the normal flow of program execution.
You can use Objective-C and Swift files together in a single project, no matter which language the project used originally. This makes creating mixed-language app and framework targets as straightforward as creating an app or framework target written in a single language.
Exception handling is made available in Objective-C with foundation class NSException. @try − This block tries to execute a set of statements. @catch − This block tries to catch the exception in try block.
You throw (or raise) an exception by instantiating an NSException object and then doing one of two things with it: Using it as the argument of a @throw compiler directive. Sending it a raise message.
see this answer:
//
// ExceptionCatcher.h
//
#import <Foundation/Foundation.h>
NS_INLINE NSException * _Nullable tryBlock(void(^_Nonnull tryBlock)(void)) {
@try {
tryBlock();
}
@catch (NSException *exception) {
return exception;
}
return nil;
}
Not the answer I was hoping for, unfortunately:
Although Swift error handling resembles exception handling in Objective-C, it is entirely separate functionality. If an Objective-C method throws an exception during runtime, Swift triggers a runtime error. There is no way to recover from Objective-C exceptions directly in Swift. Any exception handling behavior must be implemented in Objective-C code used by Swift.
Excerpt From: Apple Inc. “Using Swift with Cocoa and Objective-C (Swift 2.1).” iBooks. https://itun.es/ca/1u3-0.l
My next plan of attack is to add an Objective-C function I can call out to that will wrap the attempt in @try
/@catch
. This really sucks, Apple.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With