2014-09-23 84 views
-1
@interface Rectangle 
@property (retain) UIView *view; 
@end 

@implementation Rectangle 

CGRect frame = CGMakeRect(); 
self.view = [[UIView alloc] initWithFrame:frame] 
Student *student=[[Student alloc]init]; 
[student release];       // not using this but using dealloc on it see below 
  • (void)dealloc {_view release; [super dealloc]; [学生dealloc]; } @end

我的问题是: 这里我们为什么要解除超对象的内存????如果我们释放释放它的学生的记忆会发生什么?我必须手动释放声明为保留的属性吗?

+0

问自己为什么不使用ARC(自动参考计数)。 – rmaddy 2014-09-23 18:33:23

+0

并找到一个现代化的教程。 '@ synthesize'行不需要。 – rmaddy 2014-09-23 18:34:10

+1

半无关,但如果你没有使用ARC,并且像你在那里重写-dealloc那样,你必须在它的末尾调用[super dealloc]。否则,你会泄漏物体。 – 2014-09-23 18:40:34

回答

1

retaindealloc不恭维。 retainrelease是补充,分别添加到对象的引用计数和从中减去。

如果你的合成二传手是retain,那么你的dealloc应该做release(和[super dealloc])。

现代的方法是使用ARC,降@synthesize,始终参阅您的属性与合成的getter和setter方法,就像这样:

id foo = self.property; 
self.property = foo; 

init,它是更好地说:

_property = foo; 
+0

就像说学生*学生= [[Student alloc] init];然后[学生发布];它并像上面那样使用dealloc然后[super dealloc] dealloc方法释放哪个对象?以及为什么我们必须释放超级对象? – 2014-09-23 20:48:32

+0

Dealloc是一个令人困惑的名字。它不会释放对象,它会警告对象将释放它,使对象有机会释放其保留的任何对象。调用super dealloc调用继承的dealloc,它将释放由超类定义的属性。 – danh 2014-09-23 20:58:47

+0

这是一个关于这个主题的好文档,是在ARC推出之后编写的。现代化的方法是使用ARC,这可以简化很多。但是,您正在学习旧方法,因为它会帮助您更好地理解ARC。 http://rypress.com/tutorials/objective-c/memory-management.html – danh 2014-09-23 21:00:52

相关问题