【问题标题】:What are the pros and cons of these different dealloc strategies?这些不同的dealloc策略的优缺点是什么?
【发布时间】:2011-05-06 18:31:48
【问题描述】:

关于释放属性,我在 iOS 中看到了几种不同的内存管理方法。在与同事讨论了一番之后,利弊在我的脑海中变得模糊不清。

我希望获得一个利弊总结,这将使我自己和其他人能够轻松地选择默认方法,同时仍然了解何时进行例外处理。以下是我见过的 3 种变体:

假设@property (nonatomic, retain) MyObject *foo;

// Release-only. Seems to be the favored approach in Apple's sample code.
- (void)dealloc {
    [foo release];
    [super dealloc];
}

// Property accessor set to nil.
- (void)dealloc {
    self.foo = nil;
    [super dealloc];
}

// Release, then nil.
- (void)dealloc {
    [foo release];
    foo = nil;
    [super dealloc];
}

如果您要添加不同的变体,请在此处发表评论,我将编辑操作。

【问题讨论】:

  • +1 一个关于一个有点神秘的话题/大会的好问题。我个人在deallocrelease,并在viewDidUnload 方法中将属性设置为nil(对于非IBOutlet 属性)。我不知道是否有对此有明确的答案,但我期待阅读一些答案。

标签: ios dealloc memory-management


【解决方案1】:

版本(1):是最好的。其他每个都有可能有害的属性。

版本(2):一般建议不要在dealloc(或init)中使用访问器。这背后的原因是对象正在被拆除(或创建)的过程中并且处于不一致的状态。如果您正在编写一个库,而其他人稍后可能会覆盖访问器而不知道当对象处于不一致状态时可能会调用它,则尤其如此。 (当然,如果参数不是 CGRectZero,即使是 Apple 有时也会违反此规则 -[UIView initWithFrame:] 调用 -[UIView setFrame:],这可以使调试变得有趣。

版本(3);将 ivar 设置为 nil 没有任何用处,实际上它可能会掩盖错误并使调试更加变得困难。要了解为什么这是真的,请考虑以下代码,假设 myObject 有一个版本 (3) dealloc

FastMovingTrain* train = [[FastMoving alloc] init];
MyObject* myObject = [[MyObject alloc] init];
myObject.foo = train;
[train release];
// my myObject.foo is the only thing retaining train
...

....
[myObject release];

// Because of version (3) dealloc if myObject
// points to the dealloced memory this line 
// will silently fail... 
[myObject.foo applyBrakes];

有趣的是,这段代码提供了一个机会来演示在release 确实有意义之后将变量设置为nil。通过如下修改,可以使代码更具弹性。

FastMovingTrain* train = [[FastMoving alloc] init];
MyObject* myObject = [[MyObject alloc] init];
myObject.foo = train;
[train release];
// my myObject.foo is the only thing retaining train
...

....
[myObject release];
myObject = nil;

// This assertion will fail.
NSAssert(myObject, @"myObject must not be nil");
[myObject.foo applyBrakes];

只要我的 0.02 美元。

【讨论】:

  • 我希望在这里更精确一点。比如,是“没什么好处”还是“一点好处都没有”?如果“不多”,又有什么小好处呢?听起来#2 是个坏主意,那么如何在#1 和#3 之间进行选择。请记住,这里的想法是提供程序员团队可以用来为其编码指南提供信息的客观事实。
  • 我想这是一个公平的观点。答案是没有任何好处,甚至可能是有害的。我会编辑答案。
  • 顺便说一句,Google Objective-C 风格指南有很多明智的建议google-styleguide.googlecode.com/svn/trunk/objcguide.xml 它也链接到 Apple 编码指南。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-22
  • 1970-01-01
  • 2014-01-24
  • 2016-10-08
相关资源
最近更新 更多