Why is `&` (ampersand) put in front of some method parameters?

后端 未结 3 1016
面向向阳花
面向向阳花 2020-12-23 20:49

I\'ver wondered, why is it that in front of an NSError, such as below, do we put: &error and not error?

E.g.

NSArray *r         


        
3条回答
  •  青春惊慌失措
    2020-12-23 21:08

    Essentially, the root of the issue is a hack for wanting to return a second (optional) object.

    How can we do this, as we can only return one thing? Well, we could return some sort of (return_value, error) tuple, but that's a bit unwieldy. We can have as many parameters as we like though, can we do something with those...

    So, methods/functions can't modify their parameters (to be precise, they operate with a copy, so any modifications they make are local). That is to say (concurrency issues aside) the value of fetchRequest before the message in your question will be equal to the value of fetchRequest afterwards. Note the object pointed to by fetchRequest might change, but the value of fetchRequest itself won't.

    This puts us in a bit of a bind. Except, wait, we know we can happily take the value of a parameter and modify what it points to! If you look at the declaration for executeFetchRequest:error: you'll see it takes an NSError**. That's "a pointer to a pointer to an NSError". So, we can initialise an empty/dangling NSError*, find the address of it (with the unary & operator), and pass that in. The method can then assign to the NSError* pointed to by this.

    Voila, we effectively have optional additional return values.

提交回复
热议问题