Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does NSError need double indirection? (pointer to a pointer)

This concept seems to trouble me. Why does an NSError object need its pointer passed to a method that is modifying the object? For instance, wouldn't just passing a reference to the error do the same thing?

NSError *anError; [myObjc doStuff:withAnotherObj error:error]; 

and then in doStuff:

 - (void)doStuff:(id)withAnotherObjc error:(NSError *)error   {     // something went bad!     [error doSomethingToTheObject];  } 

Why doesn't the above work like most other object messaging patterns work? Why must instead we use error:(NSError **)error?

like image 685
Coocoo4Cocoa Avatar asked May 24 '09 04:05

Coocoo4Cocoa


People also ask

Why do we need double pointer?

The first pointer is used to store the address of the variable. And the second pointer is used to store the address of the first pointer. That is why they are also known as double pointers.

What is a double pointer in C?

Master C and Embedded C Programming- Learn as you go A pointer is used to store the address of variables. So, when we define a pointer to pointer, the first pointer is used to store the address of the second pointer. Thus it is known as double pointers.


1 Answers

Quite simply:

if you pass a pointer to an object to your function, the function can only modify what the pointer is pointing to.

if you pass a pointer to a pointer to an object then the function can modify the pointer to point to another object.

In the case of NSError, the function might want to create a new NSError object and pass you back a pointer to that NSError object. Thus, you need double indirection so that the pointer can be modified.

like image 190
rein Avatar answered Oct 11 '22 18:10

rein