Objective C (pass by reference)

1.5k views Asked by At

I'm learning about passing NSError pointers and the book talks about the pointer "becoming" an instance of an NSError.

I have no background in computer science but this seems wrong.

Does a pointer become an object, or does it point to a future allocation of memory that occurs at instantiation?
Does the object get initialized and the pointer remains where it is in memory?

And finally, what are the specific things that happen when an object instantiates specifically in the context of NSError and the pointer I passed to the method?

2

There are 2 answers

2
Sergey Kalinichenko On

the book talks about the pointer "becoming" an instance of an NSError.

This is wrong. The pointer remains a pointer. However, since all objects in Objective-C are referenced through pointers, NSError pointers are passed by double pointers, i.e. NSError**:

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

After you make this call when errorCondition is true,

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

error will be referencing a newly created NSError object, letting you pass a new instance back to the caller. This becomes handy when more than one object could be returned from a method invocation.

1
nielsbot On

I made a diagram I hope explains what's happening. The boxes on the left show what the program variables contain as the code runs. The right side shows pseudocode for the app. You can see how an NSError reference is returned to the caller of -doSomething:...

enter image description here