Search code examples
iosobjective-cuiwebviewuiwebviewdelegate

NSAssert not work in uiwebview delegate method


In a UIWebView's delegate method webView:shouldStartLoadWithRequest:navigationType:, I put an NSAssert there, but it just output a log, instead of terminating. Here is my code:

- (BOOL)webView:(UIWebView *)webView
shouldStartLoadWithRequest:(NSURLRequest *)request
            navigationType:(UIWebViewNavigationType)navigationType
{
    NSAssert(NO,@"assertion in delegate");
    return YES;
}

and the output:

*** WebKit discarded an uncaught exception in the webView:decidePolicyForNavigationAction:request:frame:decisionListener: delegate: assertion in delegate


Solution

  • NSAssert raises an Objective-C exception and these can be caught, so it doesn't guarantee your program will be aborted. Using it in your own code is generally fine, but if your code is called by a framework - such as when a delegate is invoked - it depends on what the framework does. As you have discover WebKit catches exceptions and discards or handles them itself.

    The simple solution is to use the standard assert() function. This takes a single Boolean expression and will abort the program printing out the expression, file name and line number of the assertion. This function does not use Objective-C exceptions, it uses the standard abort() function, and so cannot be caught.

    HTH