问题
if (url_leng)
{
NSString *open_string;
if (g_system_status.language_code == 0)
open_string = @"Open";
else if (g_system_status.language_code == 1)
open_string = @"Abrir";
[open_string retain];
[alert addButtonWithTitle : open_string];
g_scan_result = targ_url;
}
Consider the above code segment. My question is about the "retain" statement. Somehow I need the retain statement to make the code work. My only explanation is when open_string goes out of scope, a release call will be made against it. And thus a retain call is needed to hold the value.
Hope somebody could confirm this ...
Also wish to ask if release statements for the strings are needed after the conditional block ?
Update : (After reading through your kind suggestions and valuable insights)
Have tried the following amendment :
if (url_leng)
{
if (g_system_status.language_code == 0)
[alert addButtonWithTitle : @"Open"];
else if (g_system_status.language_code == 1)
[alert addButtonWithTitle : @"Abrir"];
else
[alert addButtonWithTitle : @"Open"];
g_scan_result = targ_url;
}
Everything seems to be ok now (even without the retain statement).
回答1:
The retain
is definitely not needed in this code. If you are having issues, it is not here. Once open_string
is assigned to the alert, you don't need it anymore. You must have a memory management issue elsewhere.
Perhaps the issue is if the language_code
is other than 0 and 1. In this case you never properly initialize open_string
. You should at least assign nil or handle this other case in some way.
Consider ARC and make your life so much easier.
回答2:
open_string
is an NSString
pointer pointing to string literal. String literals live on the stack. In your code where you are passing reference to string literal Copy them onto heap if you want to hold on to that data. If you own an object (i.e., called retain/copy/new/alloc on an object) you are responsible to release it, otherwise you would be leaking memory.
来源:https://stackoverflow.com/questions/13132101/should-i-retain-nsstring-when-it-points-to-a-literal