Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSError * vs NSError **

I realize that this is similar to an existing post here, What's the Point of (NSError**)error?, but my question is a little different. I understand how the double pointer works, and how this is the common iOS API error pattern. My question is more around the single pointer, and why this code doesn't work:

- (BOOL)someMethodWithError:(NSError *)error
{
  ...
  if( errorOccured )
  {
    NSError *e = [[[NSError alloc] initWithDomain:@"" code:1 userInfo:nil] autorelease];
    error = e;
    return NO;
  }

  return YES;
}

implemented using:

NSError *error = nil;
if( ![someObj someMethodWithError:error] )
{
  NSLog(@"Error: %@", [error localizedDescription]);
}

Why doesn't the assignment in the method implementation reassign the pointer to the new NSError object?

like image 447
Eric Avatar asked Feb 22 '12 05:02

Eric


People also ask

What is NSError?

Information about an error condition including a domain, a domain-specific error code, and application-specific information.

What is NSError domain?

The core attributes of an NSError object—or, simply, an error object—are an error domain, a domain-specific error code, and a “user info” dictionary containing objects related to the error, most significantly description and recovery strings.

What is NSError object made of?

The core attributes of an NSError object are an error domain (represented by a string), a domain-specific error code and a user info dictionary containing application specific information.

How many parts of NSError object?

Each NSError object encodes three critical pieces of information: a status code , corresponding to a particular error domain , as well as additional context provided by a userInfo dictionary.


1 Answers

I find that it helps to think of a pointer as just an integer. (That's what it is.)

Look at your example with an int.

-(BOOL)someMethodWithError:(int)error
{
     error =100;
     return NO;
}

That integer is pass by value. after that function is called error will not change.

   error  = 123;
  [self someMethodWithError:error];
  //error is = 123;

The pointer is the same thing. It's pass by value.

  NSError * error; //this assigns this to a value in memory.
  NSLog(@"%p",error);
  [self someMethodWithError:error];
  NSLog(@"%p",error); // the value of error will not have changed.

if you want the pointer to change you need to send in a pointer to that pointer and change it. It is confusing but draw yourself a diagram of memory and think about it. :)

like image 85
madmik3 Avatar answered Oct 29 '22 12:10

madmik3