Using double pointers with functions
Obviously is a technique that is not heavily used, but it comes handy some times. Methods in objective-C can return up to one argument. Double pointers can help you “return” more than one.
How is this useful,
For example, two methods:
// interface - (UIImage*)logoForTag:(int)aTag; - (NSString*)titleForTag:(int)aTag; // implementation - (UIImage*)logoForTag:(int)aTag { switch (aTag) { case 0: return [UIImage imageNamed:@"0"]; break; case 1: return [UIImage imageNamed:@"1"]; break; //.. default: break; } return nil; } - (NSString*)titleForTag:(int)aTag { switch (aTag) { case 0: return [NSString stringWithFormat:@"0"]; break; case 1: return [NSString stringWithFormat:@"1"]; break; //.. default: break; } return nil; }
We passing the same tag and we are doing the same comparison with the switch statement.
It already obvious that things could be different, THIS IS A HINT. you see duplicated code.
So, we want one method that does that:
- (void)setTitle:(NSString*)title andImage:(UIImage*)image forTag:(int)aTag // calling the method NSString *string = nil; UIImage *image = nil; [singlePointerMethod setTitle:string andImage:image forTag:0]; NSLog(@"%@,%@",string ,image); // NULL , NULL
But wait, this does not work
Why? Well, passing a pointer to your function it can only modify the pointer that is pointing to. In this case nil, the objects have not ben allocated yet. We cannot return the change to the caller.
So the solution of double pointers or “pointer to pointer”. Passing a pointer to a pointer to the function we can modify the pointer to point to another object. This allows us to pass a pointer to a function and modify it.
// interface - (void)setTitle:(NSString**)title andImage:(UIImage**)image forTag:(int)aTag // implementation - (void)setTitle:(NSString**)title andImage:(UIImage**)image forTag:(int)aTag { switch (aTag) { case 0: *image = [UIImage imageNamed:@"0"]; *title = [NSString stringWithFormat:@"0"]; break; case 1: *image = [UIImage imageNamed:@"1"]; *title = [NSString stringWithFormat:@"1"]; break; //.. default: break; } } // usage NSString *string = nil; UIImage *image = nil; [singlePointerMethod setTitle:&string andImage:&image forTag:0]; NSLog(@"%@,%@",string ,image); // log 0,<UIImage: 0x685dc10>