Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use pointers in Objective c

I have seen some iOS developpers using code like this :

- (void)setupWebView:(UIWebView**)aWebView {
 UIWebView *webview = [[UIWebView alloc] init];
.....

 if (*aWebView) {
        [*aWebView release];
    }

    *aWebView = webview;
}

Do you know what'is this mean and why we use this ? thanks

like image 779
samir Avatar asked Nov 26 '22 22:11

samir


2 Answers

- (void)setupWebView:(UIWebView**)aWebView {

That is awful. You should never have a method that returns void, but sets an argument by reference unless:

• there are multiple arguments set

• the method is prefixed with get

That method should simply return the created instance directly. And this just makes it worse -- is flat out wrong:

 if (*aWebView) {
    [*aWebView release];
 }

 *aWebView = webview;
  1. it breaks encapsulation; what if the caller passed a reference to an iVar slot. Now you have the callee managing the callers memory which is both horrible practice and quite likely crashy (in the face of concurrency, for example).

  2. it'll crash if aWebView is NULL; crash on the assignment, specifically.

  3. if aWebView refers to an iVar slot, it bypasses any possible property use (a different way of breaking encapsulation).

like image 188
bbum Avatar answered Jan 09 '23 01:01

bbum


It is a method to initialize a pointer. The first line allocates the object. The if statement makes sure that the passed in pointer-to-a-pointer is not already allocated, if it is it releases it. then it sets the referenced pointer to the newly allocated object.

like image 39
Rocky Pulley Avatar answered Jan 09 '23 03:01

Rocky Pulley