ios - addSubview 的内存泄漏故障排除

标签 ios memory-leaks addsubview

在使用 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/

相关文章:

iOS - 当好友离线时在 XMPP 聊天应用程序上发送推送通知

ios - 在 iOS 中更改 GMSMapView 默认 map 背景颜色

objective-c - xib 文件中的 addSubviews 包含两个或多个自定义 View

iphone - UIView类中addSubview和insertSubview的区别

android - 为什么在创建 Intent 实例时传递 'this'?

ios - UIView subview 的顺序?

ios - 如何阻止 TableViewCell 重复图像

ios - 错误域 = com.apple.healthkit = 3 "Workout Session is Not Current"错误?

IOS分配的对象在这个执行路径后面没有被引用保留计数+1

go - 我使用 pprof 的 golang 程序分析显示内存在 std/json 包中的 json (* decodeState) objectInterface 处增加