So, I saw this:
error:(NSError **)error
in the apple doc's. Why two stars? What is the significance?
So, I saw this:
error:(NSError **)error
in the apple doc's. Why two stars? What is the significance?
The double star (**
) notation is not specific to initializing a variable in a class. It is simply a double indirect reference to an object.
float myFloat; // an object
float *myFloatPtr; // a pointer to an object
float **myFloatPtrPtr; // a pointer to a pointer to an object
myFloat = 123.456; // initialize an object
myFloatPtr = &myFloat; // initialize a pointer to an object
myFloatPtrPtr = myFloatPtr; // initialize a pointer to a pointer to an object
myFloat; // refer to an object
*myFloatPtr; // refer to an object through a pointer
**myFloatPtrPtr; // refer to an object through a pointer to a pointer
*myFloatPtrPtr; // refer to the value of the pointer to the object
Double pointer notation is used where the caller intends that one of its own pointers need to be modified by a function call, so the address of the pointer, instead of the address of the object, is passed to the function.
An example might be the use of a linked list. The caller maintains a pointer to the first node. The caller invokes functions to search, add, and remove. If those operations involve adding or deleting the first node, then the caller's pointer has to change, not the .next pointer in any of the nodes, and you need the address of the pointer to do that.
In C, a double star is a pointer to a pointer. There are a couple of reasons to do this. First is that the pointer might be to an array of pointers. Another reason would be to pass a pointer to a function, where the function modifies the pointer (similar to an "out" parameter in other languages).
A "double star" is a pointer to a pointer. So
NSError **
is a pointer to a pointer to an object of typeNSError
. It basically allows you to return an error object from the function. You can create a pointer to anNSError
object in your function (call it*myError
), and then do something like this:to "return" that error to the caller.
In reply to a comment posted below:
You can't simply use an
NSError *
because in C, function parameters are passed by value—that is, the values are copied when passed to a function. To illustrate, consider this snippet of C code:The reassignment of
x
inf()
does not affect the argument's value outside off()
(ing()
, for example).Likewise, when a pointer is passed into a function, its value is copied, and re-assigning will not affect the value outside of the function.
Of course, we know that we can change the value of what
z
points to fairly easily:So it stands to reason that, to change the value of what an
NSError *
points to, we also have to pass a pointer to the pointer.