1

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?

Community
  • 1
  • 1
rubergly
  • 878
  • 8
  • 20

1 Answers1

4

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;
andyvn22
  • 14,696
  • 1
  • 52
  • 74
  • This was exactly my first pass. But then it wouldn't compile, so I tried to rationalize it with a poor understanding of pointers. I thought `*a = b` would actually change memory that `a` is pointing at to contain `b`, and so I thought this wouldn't work with `BOOL`s since I assumed every `YES` and `NO` is the same memory; upon second thought, this is bogus and `*a = b` clearly just updates `a` to point to the memory containing `b`. I honestly have no clue why it wouldn't compile before; it's working fine now, whoops. – rubergly Sep 01 '11 at 05:14
  • 1
    Actually, that's incorrect. What `*a = b` does is dereference `a` and set the result to `b`, so `a` does not change (it remains a pointer to the same spot in memory); what happens is that same spot in memory is rewritten to contain `b`. – andyvn22 Sep 01 '11 at 05:16
  • 2
    Do check for NULL. If it is NULL and that isn't allowed, throw an NSInvalidArgumentException. –  Sep 01 '11 at 05:20