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?
Information about an error condition including a domain, a domain-specific error code, and application-specific information.
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.
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.
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.
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. :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With