【发布时间】: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) 中的
tmpAttributedString,只有一个NSAttributedString指针并且没有像 (2) 中的临时NSString?是否可以? (第二个init依赖于第一个init。)编译器在场景 (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