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];
So, we increased the retention counter before assigning it (getting a link) to any object, and after that - locating this variable locally.
What all.