Objective C (pass by reference)

I learn about passing pointers NSError

, and the book says that a pointer "becomes" an instance NSError

.

I have no background in computer science, but it doesn't seem right.

Is a pointer an object or does it point to a future memory allocation that occurs when the instance is instantiated?
Is the object initialized and the pointer stays where it is in memory?

And finally, what are the specific things that come up when an object is created specifically in the context NSError

and the pointer that I passed to the method?

+3


source to share


2 answers


the book says that a pointer "becomes" an instance NSError

.

It is not right. The pointer remains a pointer. However, since all objects in Objective-C are referenced through pointers, pointers NSError

are passed using double pointers, i.e. NSError**

:

-(void)checkError:(NSError**)errPtr {
    if (errorCondition) {
        *errPtr = [NSError errorWithDomain:... code:... userInfo:...];
    }
}

      



After making this call, when errorCondition

true,

NSError *error = nil;
[self checkError:&error];

      

error

will refer to the newly created object NSError

, allowing you to pass the new instance back to the caller. This comes in handy when more than one object can be returned from a method call.

+2


source


I made a diagram, hopefully explains what's going on. The boxes on the left show what the program variables contain when the code runs. The right side shows the pseudocode for the application. You can see the NSError reference being returned to the caller -doSomething:

...



enter image description here

+2


source







All Articles