0

I want to log some errors generated when using a WebView. For instance:

- (void)webView:(UIWebView *)aWebView didFailLoadWithError:(NSError *)error{
    NSString * domain;
    domain  = [error domain];
    NSLog(@"%@",error);
    if ( domain == NSURLErrorDomain ) {NSLog(@"log me");}
}

I found this does not work on Xcode 6.1 and iOS8.1-simulator. It used to work on previous iOS versions (tested with Xcode 6.1 and iOS7-simulator). What am I missing?

Here is the console output:

2014-11-06 03:42:15.295 MyApp debug[21897:3606481] Error Domain=NSURLErrorDomain Code=-1012 "The operation couldn’t be completed. (NSURLErrorDomain error -1012.)" UserInfo=0x7a7531c0 {NSErrorFailingURLKey=https://www.google.fr/}

And some debugging when using the iOS8-simulator:

(lldb) p NSURLErrorDomain (void *)
$0 = 0x0064dacc
(lldb) po domain
NSURLErrorDomain

(lldb) p domain (NSString *) $2 = 0x0064dacc @"NSURLErrorDomain"

subzero
  • 3,420
  • 5
  • 31
  • 40

2 Answers2

3

Just to expand on Aaron's answer: What you were doing was always wrong, but it may have worked because of an accident about the way Cocoa stores strings. domain == NSURLErrorDomain tests whether these are effectively one and the same object. Well, maybe under some conditions they are; Cocoa may sometimes behave efficiently by treating two different instances of, say, the literal @"howdy" as references to one and the same object. But clearly it makes no sense to count on that behavior. It's just an implementation detail.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • Even if both strings are in theory the "same" constant, from the same class, there may be two copies of the constant, in two different modules. This possibility makes the use of `==` flakier still. – Hot Licks Nov 06 '14 at 03:17
1

Since you're comparing strings, you're going to want to use isEqualToString: like so:

if ( [domain isEqualToString:NSURLErrorDomain] ) {NSLog(@"log me");}
Aaron Wojnowski
  • 6,352
  • 5
  • 29
  • 46
  • My understanding is that it should work also (comparing pointers). http://stackoverflow.com/questions/538996/constants-in-objective-c/539191#539191 – subzero Nov 06 '14 at 03:10
  • I had the same issue in my app, actually. Previously it was working fine but recently ceased to work, and `isEqualToString:` fixed it up since it's (obviously) a surefire way to compare the strings. `matt` gave a more thorough explanation as well. – Aaron Wojnowski Nov 06 '14 at 03:12
  • I agree with what you and matt says. Comparing 2 strings must be done with 'isEqualToString'. My intention when doing 'domain == NSURLErrorDomain' was to compare the pointers. And, according to the LLDB output they are pointing to the same address. Right? – subzero Nov 06 '14 at 03:27