Search code examples
objective-ciosnsstringretaincount

Should I retain NSString when it points to a literal?


    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).


Solution

  • 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.