0

使用 addSubview 时防止内存泄漏的正确方法是什么?我收到 Instruments 的投诉,称此代码存在泄漏。我究竟做错了什么?

示例代码:

我的.h

@interface MyCustomControl : UIControl {
    UILabel *ivarLabel;
}

@property (nonatomic, retain) UILabel       *ivarLabel;

我的

@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];
}

谢谢你的帮助。

4

1 回答 1

2

而不是这个:

  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。减去release上的dealloc,给你1。这就是你有泄漏的原因。

于 2013-03-07T21:56:38.130 回答