nein.
nein.

Reputation: 2127

Creating NSError * results in application crash

I have the following situation:

My domain class gets some input validates it, and if validation passes it proceeds with saving data. When control flow reaches the if statements, the application crashes

- (BOOL)createGmailAccountWithName:(NSString *)name
                                 email:(NSString *)email
                           andPassword:(NSString *)password
                                 error: (NSError **) error {
  if (!name || name.length == 0) {
    *error = [self createError:@"name"];
    return NO;
  }

  if (!email || email.length == 0) {
    *error = [self createError:@"email"];
    return NO;
  }

  if (!password || password.length == 0) {
    *error = [self createError:@"password"];
    return NO;
  }

  //..
}


-(NSError *) createError: (NSString *) field {

  NSString *errorMessage = [NSString stringWithFormat:@"Property %@ is required", field];

  NSDictionary *userInfo = @{
    NSLocalizedFailureReasonErrorKey: NSLocalizedString(errorMessage, nil)
  };

  NSError *error = [NSError errorWithDomain:ACCOUNT_STORE_ERROR_DOMAIN
  code:-1
  userInfo:userInfo];

  return error;
}

When I comment out all lines where the validation happens, the application does not crash. I have no idea why this is happening. Can anyone point me into the right direction?

Upvotes: 0

Views: 990

Answers (1)

Ben Flynn
Ben Flynn

Reputation: 18932

If you have this method:

- (BOOL)createGmailAccountWithName:(NSString *)name
                             email:(NSString *)email
                       andPassword:(NSString *)password
                             error: (NSError **) error

Folks are probably going to call it either like this:

NSError *error;
[accountCreator createGmailAccountWithName:@"Ben" 
                                     email:@"[email protected]" 
                               andPassword:@"pwd"
                                     error:&error];
if (error)
{
    NSLog(@"Hey I got an error: %@", error);
}

Or like this:

[accountCreator createGmailAccountWithName:@"Ben"
                                     email:@"[email protected]"
                               andPassword:@"pwd"
                                     error:NULL];
// I couldn't care less about an error

In the second case, your code will will try to dereference **error, *error is not a valid pointer and would cause a crash.

Upvotes: 3

Related Questions