简体   繁体   中英

How to pass the equivalent of nil for an (NSError **)

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?

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.

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.

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];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM