设置 NSString 属性的默认值

发布于 10-03 18:20 字数 597 浏览 6 评论 0原文

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

我知道在类的 init 和 dealloc 方法中使用访问器方法是不安全的。我经常想为字符串常量分配默认值。推荐的方法是什么(考虑到 iVar 将在 dealloc 方法中释放)?

例如,我知道以下内容是不安全的:

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

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

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

    return self;
}

可以吗,或者建议这样做:

identifier = [@"fireSpell01" retain];

或者我必须这样做:

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

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

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

Or must I do this:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

匿名的好友2024-10-10 18:20:45

只需这样做:

identifier = @"fireSpell01";

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

您要避免的是在 initdealloc 方法中使用属性设置器。由于 setter 可能会产生依赖于某些状态值的副作用,因此您不希望在部分构造/部分销毁的对象上调用它们。最好直接分配给 ivars 并在 init 期间跳过 setter。

Just do this:

identifier = @"fireSpell01";

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.

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文