Question

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?

Was it helpful?

Solution 2

Take a look at: Why is `&` (ampersand) put in front of some method parameters?

In short: you need to pass a pointer to the NSError pointer, so save: can assign an occasional error to savingError.

OTHER TIPS

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".

The & represents address of the object.When we pass objects to a method then a copy of the object has been passed to it. What ever changes made to that object within that method ,wont effect the object that is used with method calling .

When we use & , actually we pass the address of the object, so that what ever change we make to the object with in that method will effect the object that is used as argument in method calling.

Here in save: method, we are passing a object of NSError class. If some error occurs during the time of Save method(process) can be found by using this NSError object.

[savingError localizedDescription];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top