Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective C (pass by reference)

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?

like image 782
Alexander Bollbach Avatar asked Jun 17 '15 02:06

Alexander Bollbach


2 Answers

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

like image 57
nielsbot Avatar answered Oct 13 '22 19:10

nielsbot


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.

like image 35
Sergey Kalinichenko Avatar answered Oct 13 '22 20:10

Sergey Kalinichenko