Question

My class has member __strong NSError *authError; I would like to catch and create it in one method and check in another. So if error occurs in method 1:

if([returnString rangeOfString:@"dd"].location != NSNotFound) {  
        NSMutableDictionary *errorDetail = [NSMutableDictionary dictionary];
        [errorDetail setValue:@"Wrong user crediantials" forKey:NSLocalizedDescriptionKey];
        authError = [NSError errorWithDomain:@"mydomain" code:101 userInfo:errorDetail];

        return nil;
    }

I assigned it directly to the authError class member. But after stepping last breket authError becomes nil. And in method 2:

if(authError != nil){
        return NO;
    }

condition returns YES

Some additional info: method 2 is shouldPerformSegueWithIdentifier Could someone give me a hint?

Was it helpful?

Solution

The problem here has to do with the definition of the word "after". You are setting your instance variable in method 1 and fetching it in method 2. But this tells you nothing about the true order of operations. If it happens that method 2 is called before method 1 has a chance to run, then method 2 will find that your instance variable is nil (because that is its autoinitialized value).

My book has a riff on this very topic (by "entry point" I mean a method that is called by the runtime):

Adding to your challenges is the fact that you can’t really know precisely when an entry point will be called. The documentation may give you a general sense, but in most cases it doesn’t guarantee anything about precisely when events will arrive and in what order. What you think is going to happen, and even what the documentation leads you to believe is going to happen, might not be quite what really does happen. Your own code can trigger unintended events. The documentation might not make it clear just when a notification will be sent. There could even be a bug in Cocoa such that events are called in a way that seems to contradict the documentation. And you have no access to the Cocoa source code, so you can’t work out the underlying details. Therefore I also recommend that as you develop your app, you instrument your code heavily with caveman debugging (NSLog; see Chapter 9). As you test your code, keep an eye on the console output and check whether the messages make sense. You may be surprised at what you discover.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top