当它指向文字时,我应该保留NSString吗? [英] Should I retain NSString when it points to a literal?

查看:53
本文介绍了当它指向文字时,我应该保留NSString吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

    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;               
    }

考虑上面的代码段.我的问题是关于保留"声明的.我需要以某种方式使代码起作用.我唯一的解释是,当open_string超出范围时,将对其进行释放调用.因此,需要保留调用来保存该值.

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)

尝试了以下修改:

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

推荐答案

此代码中绝对不需要retain.如果您遇到问题,则不在这里.将open_string分配给警报后,就不再需要它了.您必须在其他地方遇到内存管理问题.

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.

也许问题是language_code不是0和1.在这种情况下,您永远不会正确初始化open_string.您至少应指定nil或以其他方式处理此其他情况.

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.

考虑ARC,让您的生活变得如此轻松.

Consider ARC and make your life so much easier.

这篇关于当它指向文字时,我应该保留NSString吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆