【问题标题】:How to release object which init it self如何释放本身的对象
【发布时间】:2016-12-15 06:58:17
【问题描述】:

在编写 Objective-C 时,了解内存的管理方式很重要,即使在 ARC 的帮助下也是如此。

这是一个代码 sn-p(非 ARC):

(1)

NSAttributedString *tmpAttrbutedString = [[NSAttributedString alloc] initWithString:@"foo" attributes:@{NSFontAttributeName:[NSFont fontWithName:@"Heiti SC" size:13.0f]}];
// how should I release tmpAttributedString here?
tmpAttributedString = [[NSAttributedString alloc] initWithString:tmpAttributedString.string attributes:@{NSForegroundColorAttributeName:[NSColor redColor]}];
[tmpAttributedString release];

这是我目前为避免内存泄漏而采取的措施:

(2)

NSAttributedString *tmpAttrbutedString = [[NSAttributedString alloc] initWithString:@"foo" attributes:@{NSFontAttributeName:[NSFont fontWithName:@"Heiti SC" size:13.0f]}];
NSString *tmpString = tmpAttrbutedString.string;
[tmpAttrbutedString release];

tmpAttributedString = [[NSAttributedString alloc] initWithString:tmpString attributes:@{NSForegroundColorAttributeName:[NSColor redColor]}];
[tmpAttributedString release];

我的问题是:

  1. 我应该如何释放 (1) 中的 tmpAttributedString,只有一个 NSAttributedString 指针并且没有像 (2) 中的临时 NSString?是否可以? (第二个init依赖于第一个init。)

  2. 编译器在场景 (1) 中会做什么?我的意思是 ARC 如何为它插入释放/自动释放?如果启用了 ARC,(1) 中是否存在任何内存泄漏? (当然,使用 ARC 删除了对 release 的显式调用。)

谢谢!

【问题讨论】:

  • alloc 和 init 在任何目标 C 对象的情况下只调用一次?
  • @dreamBegin 只是为了确保。你的意思是我不应该重用 NSAttributedString 指针,而应该做一个新的?
  • 你不应该只是在你初始化的第一个 NSAttributedString 上设置所有属性吗?不需要创建第二个 NSAttributedString。
  • @LucasDerraugh 抱歉,这不是一个很好的例子。我知道我在做一些不必要的工作。但是假设使用第一个属性字符串完成了更多工作,然后是第二个 alloc init。谢谢。
  • @LucasDerraugh 是的,请。欢迎您详细说明ARC如何在编译时插入release或autorelease。谢谢! ;-)

标签: objective-c automatic-ref-counting


【解决方案1】:

ARC 的规则相对简单。如果您调用 allocnewcopy,则 ARC 知道它需要在此对象超出范围时调用 release。所有其他对象都假定为autoreleased。 “超出范围”意味着返回或重新分配变量。在它看到一个变量重新分配的情况下,它会在分配给其他东西之前隐式地调用release。如果您返回一个变量,ARC 将对该变量进行autorelease 调用,以便它可以在方法范围之外持续存在;没有返回但仍然存在的任何其他现有变量(不是自动释放的)都会有一个隐式的release 发送给它们。

Apple's official transition guide 供参考。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-08
    • 2021-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-24
    相关资源
    最近更新 更多