objective-cpointersindirectionmultiple-indirection

How to pass (and set) non-objects by indirection?


NSError objects are frequently used like this (taken from this previous question):

- (id)doStuff:(id)withAnotherObjc error:(NSError **)error;

I want to achieve something similar with BOOL indirection:

- (id)doStuff:(id)withAnotherObjc andExtraBoolResult:(BOOL **)extraBool;

But I can't figure out how to get this working correctly.

For the given method specification involving NSError, the proper implementation would involve something like (again from the previous question):

*error = [NSError errorWithDomain:...];

With similar logic, it seems like this should work with BOOL indirection:

*extraBool = &YES; // ERROR! Address expression must be an lvalue or a function designator

Why doesn't this work and what is the proper way to implement this?


Solution

  • Keep in mind that with objects, you're working with a pointer (e.g., NSError*), so using this method, you wind up with a pointer to a pointer (e.g., NSError**). When working with a BOOL, though, you should use a pointer to a BOOL: that is, only one level of indirection, not two. Therefore, you mean:

    - (id)doStuff:(id)withAnotherObjc andExtraBoolResult:(BOOL *)extraBool;
    

    and subsequently:

    *extraBool = YES;