设置NSString属性的默认值 [英] Setting Default Values For NSString Properties

查看:214
本文介绍了设置NSString属性的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试确定推荐的方法来为NSString属性设置默认值.

I am trying to determine the recommended way to set default values for NSString properties.

我知道在类的init和dealloc方法中使用访问器方法并不安全.我经常有一些字符串常量,我想分配默认值.推荐这样做的方法是什么(考虑到iVar将在dealloc方法中发布)?

I understand it is not safe to use accessor methods in a class's init and dealloc methods. I often have string constants that I would like to assign default values. What is the recommend way to do this (considering the iVar will be released in the dealloc method)?

例如,我了解以下内容是不安全的:

For example I understand the following is unsafe:

@property (nonatomic, copy) NSString *identifier;
....

- (id) init
{ 
    self = [super initWithLayer:displayLayer];

    if (self != nil)
    {
        self.identifier = @"fireSpell01";
    }

    return self;
}

可以,还是建议这样做:

Is it ok, or recommend to do this:

identifier = [@"fireSpell01" retain];

还是我必须这样做:

identifier = [[NSString stringWithString:@"fireSpell01"] retain];

推荐答案

只需执行以下操作:

identifier = @"fireSpell01";

不需要retain字符串.字符串常量存在于程序的整个生命周期中,不需要保留或释放.进行[[NSString stringWithString:@"fireSpell01"] retain]只会创建不必要的副本,而且毫无意义.

There's no need to retain the string. String constants exist for the lifetime of the program and never need to be retained or released. Doing [[NSString stringWithString:@"fireSpell01"] retain] just creates an unnecessary copy and is pointless.

您要避免的是在initdealloc方法中使用属性设置器.由于setter可能具有取决于某些状态值的副作用,因此您不想在部分构造/部分破坏的对象上调用它们.直接在init期间直接分配给ivars并跳过设置器会更好.

What you want to avoid is using the property setters in the init and dealloc methods. Because setters could potentially have side effects that depend on certain state values, you don't want to call them on partially constructed/partially destroyed objects. It is much better just to assign directly to the ivars and skip the setters during init.

这篇关于设置NSString属性的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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