Issuing local variables before returning?

In objective-c, I understand that you need to free everything that you start / save / copy. Should I do this before the return ? I want to understand the release call explicitly and not use autorelease .

 -(void) someMethod { AnotherClass* ac = [[AnotherClass alloc] init]; if([ac somethingHappens]){ // Do I need to release ac here? return; } [ac doSomethingElse]; [ac release]; } 

Thanks!

+4
source share
2 answers

Yes, you need to free the variables, however you exit the method.

This is pretty straight forward: when you start something, the retention counter is incremented. When you release it, it decreases. When it reaches zero, it is automatically freed (freed).

In the above code, you initialize the variable, but if it follows the return route, then the variables that save the count never become zero and therefore are never freed.

+3
source

Suppose a local variable is assigned as follows:

 NSString *placeHolder = [NSString stringWithFormat:@"%@ %@",[someObject value1], [someObject value2]]; 

Now pass this variable to an object-specific method, such as the setPlaceholder of a UISearchBar

 [self.theSearchBar setPlaceholder:placeHolder]; 

How to correctly output the assigned string 'placeHolder'?

If you assume it will auto-reclassify it:

 NSString *placeHolder = [[NSString stringWithFormat:@"%@ %@",[someObject value1], [someObject value2]] autorelease]; 

your code will crash with bad_exc_access

If you decide to free the variable after transferring to another place, for example

 [self.theSearchBar setPlaceholder:placeHolder]; [placeHolder release]; 

a runtime exception will also be thrown.

So what's wrong?

The problem is the number of deductions. The UISearchBar object is still selected, so if you release or automatically release such a variable passed by this object, the save count will remain the same

 NSLog(@"Retain count before assign to refer other object %d", [placeHolder retainCount]); [self.theSearchBar setPlaceholder:placeHolder]; NSLog(@"Retain count after referencing %d", [placeHolder retainCount]); 

So how to handle this?

Try the following:

 [placeHolder retain]; // retainCount +1 [self.theSearchBar setPlaceholder:placeHolder]; [placeHolder release]; // retainCount -1 

What have we done than? Let's look at the save account now

 NSLog(@"Retain count before doing retain %d", [placeHolder retainCount]); [placeHolder retain]; // retainCount +1 NSLog(@"Retain count after retaining it %d", [placeHolder retainCount]); 

So, we increased the retention counter before assigning it (getting a link) to any object, and after that - locating this variable locally.

What all.

+2
source

Source: https://habr.com/ru/post/1301620/


All Articles