NSError * vs NSError **

I understand that this looks like an existing post here, Error Point Error (NSError **)? but my question is a little different. I understand how a double pointer works, and how it is a common iOS API error pattern. My question is more related to a single pointer and why this code does not work:

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

using:

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

Why does the assignment in the method implementation not reassign the pointer to the new NSError object?

+7
source share
4 answers

I find this helps to think of a pointer as an integer. (What it is.)

Look at your example using int.

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

This integer is passed by value. after this function is called an error, it will not change.

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

A pointer is the same thing. It passes 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 a pointer to that pointer and change it. This is confusing, but draw a memory chart and think about it. :)

+8
source

All about double pointer.

Why is the new value not displayed? Since you never changed the contents of the object you initialized to zero. To do this, you would need to use a reference to the memory location in which the nil value was stored (a pointer to a pointer), and not just a copy of the nil value (this is what you pass using a single pointer).

This is really an ordinary thing that is worth doing in C, where part of the result of the function is "returned" through the pointer in the input arguments.

+3
source

This is how the C language works. You can take a look at this question and answer: C is a double pointer , which basically is one and the same in a different guise.

0
source

Well error , that somemethodWithError has another pointer that contains the address of the error from which someMethodWithError is raised. therefore, when you assign an object to the error pointer somemethodWithError , it will not reflect in the method error pointer where it is called

like him

 NSError * error1 = obj1; NSError * error2 = error1; 

and after that, if you assign any new object to error2, for example

 error2 = obj2; 

it will not change the value of the error pointer1, and it will still point to obj1

0
source

All Articles