why is “error:&error” used here (objective-c)
NSError *error = nil;
NSArray *array = [moc executeFetchRequest:request error:&error];
wouldn’t an object in objective-c be effectively pass-by-reference anyway?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The argument type for
error:isNSError**(i.e. a pointer to a pointer to an object). This permits themocobject to allocate and initialize a newNSErrorobject as required. It is a common pattern, especially in Cocoa.The NSError documentation gives some indication of the motivation for this approach:
Passing in an
NSError**argument allows that method to return any subclass ofNSErrorthat makes sense. If you passed inNSError*, you would have to supply an existingNSErrorobject, and there would be no way for the method to return a different object from the one you passed in.To be clear, the method could look something like this:
Note that this also allows the calling code to ignore errors by simply passing in
NULLfor theerror:parameter, as follows:Update: (in response to questions):
There are two reasons why the argument type has to be
NSError**instead ofNSError*: 1. variable scoping rules, and 2. NSError instances are imutable.Reason #1: variable scoping rules
Let’s assume that the function declaration were to look like this:
And we were to call the function like this:
When you pass in a variable this way, the function body will not be able to modify the value of that variable (i.e. the function body will not be able to create a new variable to replace the existing one). For example, the following variable assignments will exist only in the local scope of the function. The calling code will still see
error == nil.Reason #2: instances of NSError are immutable
Let’s keep the same function declaration, but call the function like this:
First of all, the variable scoping rules guarantee that
errorcan not benil, so theif (error != nil) { ...condition will always be true, but even if you wanted to check for specific error information inside theifblock, you would be out of luck because instances ofNSErrorare immutable. This means that once they are created, you cannot modify their properties, so the function would not be able to change thedomainoruserInfoof thatNSErrorinstance that you created in the calling code.