在使用 addSubview 时防止内存泄漏的正确方法是什么?我收到来自 Instruments 的投诉,说这段代码存在漏洞。我做错了什么?
示例代码:
我的.h
@interface MyCustomControl : UIControl {
UILabel *ivarLabel;
}
@property (nonatomic, retain) UILabel *ivarLabel;
我的.m
@synthesize ivarLabel;
- (id)initWithFrame:(CGRect)frame {
if ((self = [super initWithFrame:frame])) {
self.ivarLabel = [[UILabel alloc] initWithFrame:CGRectMake( 0, 0, 10, 10)];
[self addSubview:self.ivarLabel];
}
return self;
}
- (void)dealloc {
[ivarLabel release];
[super dealloc];
}
感谢您的帮助。
最佳答案
取而代之的是:
self.ivarLabel = [[UILabel alloc] initWithFrame:CGRectMake( 0, 0, 10, 10)];
这样做:
ivarLabel = [[UILabel alloc] initWithFrame:CGRectMake( 0, 0, 10, 10)];
第一个片段可以在 ARC 中使用。
但为什么呢?
内部 setter (self.ivarLabel = ...
) 将具有与此相同的逻辑:
-(void)setIvarLabel:(UILabel *)newLabel {
if (ivarLabel != value) {
[ivarLabel release];
ivarLabel = [newLabel retain];
}
}
您可以看到您执行的 alloc
([UILabel alloc]
) 加上在 if
中完成的保留,将创建一个保留计数为 2。减去 dealloc
上的 release
,得到 1。这就是泄漏的原因。
关于ios - addSubview 的内存泄漏故障排除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15282490/