Search code examples
objective-cdouble-pointer

why use double pointer when single pointer can do the work in Objective-C?


I understand the benefit of using pointer but double pointer is what I really don't understand. I was told that double pointer is used when you want the method to modify the value of param you pass in. Given the example below, 5 will be printed in log. Then why should we use double pointers in void changeInt(int **i)?

int main (int argc, const char * argv[])
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    int *a = 1;

    changeInt(&a);
    NSLog(@"%i", a);
    [pool drain];
    return 0;
}

void changeInt(int *i)
{
    *i = 5;
}

Solution

  • There's no need for a double pointer with a scalar (int). Obviously all you need is a pointer.

    But an object already is a pointer. So to do the same thing with an object, you need a double pointer. The typical use case is NSError**:

    + (id)stringWithContentsOfFile:(NSString *)path
                          encoding:(NSStringEncoding)enc
                             error:(NSError **)error