I have the following code to save an entity to the managed object context.
NSError *savingError = nil;
if ([self.managedObjectContext save:&savingError]) {
NSLog(@"Successfully saved the context.");
} else {
NSLog(@"Failed to save the context. Error = %@", savingError);
}
According to my documentation I understand the following: After inserting a new entity into the context, we must save the context. This will flush all the unsaved data of the context to the persistent store. We can do this using the save: instance method of our managed object context. If the BOOL return value of this method is YES, we can be sure that out context is saved.
What I am not clear on is the syntax after save:, specifically the ampersand '&' just before the local savingError variable. What does this tell the compiler?
The & operator basically means "address of". It takes a value and returns a pointer to that value. So in this case, &savingError is a value of type NSError** which is a pointer that holds the address of your savingError variable. The calling code can then use *error to "dereference" that pointer and get back your variable. This means it can say
*error = [NSError errorWithDomain:...]
and then in your code, the savingError variable will now be populated with the new error.
This is a fairly common programming style in C to simulate having multiple return values. Parameters like this (pointers to values, where you pass in the address of a variable and the function fills it in) are typically called "out-parameters" or "out-params".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With