Syntax of ** in objective C
-
28-04-2021 - |
Question
Simple question. What is the meaning of the double asterisk in the interface below? It's not an NSError pointer, but what?
- (BOOL)checkResourceIsReachableAndReturnError:(NSError **)error
Solution
It's a pointer to a pointer to an NSError
. It's used as an "out parameter" -- or you may want to think of it as a pointer to an NSError
instance, considering an NSObject
instance is always a pointer.
You use it like this:
NSError * outError = nil; << reserve place and a name for the out parameter
// pass the error so the client may return it to you:
BOOL ret = [obj checkResourceIsReachableAndReturnError:&outError];
if (nil != outError) { << the error was set in checkResourceIsReachableAndReturnError:
NSLog(@"Error: %@", outError); << log it
}
…
On the implementation side, it looks like this:
- (BOOL)checkResourceIsReachableAndReturnError:(NSError**)outError
{
if (self.isThingReachable) {
// okay - the caller may not be interested in the error, test it:
if (0 != outError) {
// they are interested this time!
*outError = [NSError errorWithBlahBlahBlah];
}
return NO;
}
return YES;
}
OTHER TIPS
You call it by sending a reference to an NSError*
, like so:
NSError *myError = NULL;
[foo checkResourceIsReachableAndReturnError:&myError];
if (myError) {
/* look through info, handle error, etc. */
}
The -checkResourceIsReachableAndReturnError:
method can modify the pointer myError
, including allocating space for a new NSError
. This allows you to easily check if there was an error, by simply checking if myError
is non-NULL
.
Check out this blog post: "Using NSError To Great Effect" and pay particular attention to the section "Passing Pointers to Pointers."
Also the wiki page on pointers has a section on "Multiple Indirection"