How to use pointers in Objective c

I saw some iOS developers using this code:

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

Do you know what this means and why we use it? thanks

+4
source share
3 answers
 - (void)setupWebView:(UIWebView**)aWebView { 

This is terrible. You should never have a method that returns void, but sets the argument by reference if:

β€’ there are many arguments

β€’ the method has a get prefix

This method should simply return the instantiated instance directly. And this only exacerbates the situation - a bad mistake:

  if (*aWebView) { [*aWebView release]; } *aWebView = webview; 
  • it destroys encapsulation; what if the caller passed the link to the iVar slot. Now you have a control group managing the caller’s memory, which is both terrible practice and most likely emergency (for example, when using concurrency).

  • it will work if aWebView is NULL; intended accident, in particular.

  • if aWebView belongs to the iVar slot, it bypasses any possible use of the property (another way to break encapsulation).

+41
source

This is a pointer initialization method. The first line selects the object. The if statement ensures that the one passed in in the pointer to the pointer is not yet highlighted if it frees it. then it sets the link pointer to the newly selected object.

+2
source

The answer to @bbum is probably correct, but does not take into account one aspect of the question that I see there. There are many examples in Foundation that use pointers in a method signature, so you can say that this is a common pattern. And this is probably not a beginner's mistake.

Most of these examples are similar in that they fall into one category: the API tries to avoid using exceptions and instead use NSError for crashes. But since the return value is used for BOOL , which indicates success, an NSError pointer is used as the output parameter. Only in the case of a rare error is an NSError object created, which can contain error codes and error descriptions, as well as localized descriptions and possibly even more information (for example, an array of several errors in the case of mass operations). Thus, the main success case is effective, and in the event of an error, there is some ability to report what went wrong without resorting to exceptions. This is the justification for these signatures, as I understand it.

Examples of this use can be found in both NSFileManager and NSManagedObjectContext .

You might be tempted to use pointers in other cases where you want multiple return values ​​and an array to not make sense (for example, because the values ​​are not of the same type), but as @bbum said, this is most likely better look for alternatives.

+1
source

All Articles