Releasing local variables before return?
In objective-c, I understand that you need to release anything you init/r开发者_开发百科etain/copy. Do I need to do that before a return
statement? I'm wanting to understand calling release
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!
Yes, you need to release your variables, however you exit from the method.
It's pretty straight-forward: when you init something the retain count is incremented. When you release it's decremented. When it reaches zero it's automatically deallocated (freed).
In your code above, you init the variable but if it follows the return route then the variables retain count never gets to zero and, therefore, is never deallocated.
Suppose to have a local variable assigned like the following
NSString *placeHolder = [NSString stringWithFormat:@"%@ %@",[someObject value1], [someObject value2]];
Now pass this variable to a object defined method, such as setPlaceholder of UISearchBar object
[self.theSearchBar setPlaceholder:placeHolder];
How to release in the right way the assigned string 'placeHolder' ?
If you suppose to autoreleas it:
NSString *placeHolder = [[NSString stringWithFormat:@"%@ %@",[someObject value1], [someObject value2]] autorelease];
your code will fail with a bad_exc_access
If you think to release the variable after passed to somewhere else like
[self.theSearchBar setPlaceholder:placeHolder];
[placeHolder release];
a runtime exception will throw too.
So what's wrong?
The problem is the retain count. The UISearchBar object is allocated yet, so if you release or auto-release such a variable, referred by that object, the retain count is still 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 something like the following
[placeHolder retain]; // retainCount +1
[self.theSearchBar setPlaceholder:placeHolder];
[placeHolder release]; // retainCount -1
What we did than ? Let's have a look at the retain count 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 incremented the retain count before assign it (get referenced by) to some object, and - after that - we release locally that variable.
That's all.
精彩评论