views:

85

answers:

3

I have a method that takes an (NSError **) but I don't want to pass it one. When I pass it "nil" or "NULL" I end up with "EXC_BAD_ACCESS".

The offending line is "*error = nil;"

How do I pass it the equivalent of "nil" without crashing?

+3  A: 

The offending line should be:

if (error != nil) { *error = nil; }

You're trying to dereference a null pointer, which is a surefire way to crash.

The alternative would be to pass it an NSError**, but then just ignore it afterwards.

Dave DeLong
I'll probably use the alternative since the offending line isn't in my code and so I don't really want to mess with it. Thanks for the help Dave!
Eddie Marks
+1  A: 

You have to pass it a valid pointer to something which it can modify. The standard way to do this would be:

NSError *error = nil;
[object callMethod:whatever error:&error];
invariant
+2  A: 

When you are implementing such method, you can use the following trick so that you won’t have to check for nil all the time:

- (void) doSomethingMaybeCausing: (NSError**) error
{
    NSError *dummyError = nil;
    if (error == NULL)
        error = &dummyError;
    // ...later:
    *error = [NSError …];
}

Now the caller can pass NULL if he’s not interested in the errors.

zoul
Genius. Thanks for the trick!
Eddie Marks