【问题标题】:Is it safe to assigning a static string to a property, and then release it later将静态字符串分配给属性,然后释放它是否安全
【发布时间】:2012-08-26 19:00:48
【问题描述】:

我只是在更新我的一个应用程序,我发现了一些让我大吃一惊的旧代码。我的评论通常很冗长,但我没有向自己解释我为什么这样做。

我正在展示一个 ModalView 并更新标题和 UITextField,如下所示:

addStoryItem.placeholderText = @"Foo"; //The text is always a static string.
addStoryItem.modalTitleText  = @"Bar";

在模式中,为这两个值分配属性:

@property (readwrite, assign) NSString *placeholderText;
@property (readwrite, assign) NSString *modalTitleText;

然后在modal被dismiss后在modal的dealloc中释放:

[placeholderText release];
[modalTitleText  release];

这安全/明智/可以吗?我想我可能对avoid a retain cycle 做了这个。

【问题讨论】:

  • 对字符串使用“复制”属性就可以了。在这种情况下使用“分配”是错误的。也没有保留周期,因为字符串没有对控制器的拥有引用。 (他们应该怎么做?)

标签: cocoa-touch ios5 memory-management modalviewcontroller


【解决方案1】:

你违反了一些规则:

  1. 释放你所拥有的。 (你不拥有 assign 属性。你只是侥幸逃脱,因为释放字符串文字是一个 nop)
  2. 始终复制 NSString 属性。 (赋值在这里真的很危险,对象可能会消失。同样,不适用于文字。)

您可以通过避免保留循环来证明这一点。但由于字符串(通常)不引用其他对象,循环在这里不是问题。

【讨论】:

    猜你喜欢
    • 2011-10-07
    • 1970-01-01
    • 1970-01-01
    • 2011-03-15
    • 2021-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-12
    相关资源
    最近更新 更多