将UIView添加到UIWindow会导致内存泄漏

时间:2017-06-30 13:02:38

标签: ios objective-c memory-leaks addsubview

我有这样的观点:

@interface MyView ()

@property (nonatomic, strong) UIView* subView;

@end

@implementation MyView

#pragma mark - init && dealloc

-(instancetype)init
{
    self = [super init];
    if (self){        
        [self setupSubView];
        [self setupAutoLayoutSubView];        
    }
    return self;
}

#pragma mark - setup

-(void)setupSubView
{
    _subView = [UIView newAutoLayoutView];
    [self addSubview:_subView];
}

-(void)setupAutoLayoutSubView
{
    // autolayout: to centralize the subView
    // if you don't use PureLayout, you can use the traditional way
    [_subView autoCenterInSuperview];
}

@end

当我将此视图添加到Window时,此视图上的引用计数将增加到3。


MyView* v = [[MyView alloc] init];
NSLog(@"reference counting = %ld",CFGetRetainCount((CFTypeRef)v)); //- 1

UIWindow* window = [[UIApplication sharedApplication] keyWindow];
[window addSubView:v];

NSLog(@"reference counting = %ld",CFGetRetainCount((CFTypeRef)v)); //- 3 INCORRECT

奇怪的是,如果我评论" 自动布局"部分来自方法:" setupAutoLayoutSubView ",引用计数正确(= 2)

或者如果我将我的视图添加到普通视图中,引用计数也是正确的



MyView* v = [[MyView alloc] init];
NSLog(@"reference counting = %ld",CFGetRetainCount((CFTypeRef)v)); //- 1

UIView* normalView = [[UIView alloc] init];
[normalView addSubView:v];

NSLog(@"reference counting = %ld",CFGetRetainCount((CFTypeRef)v)); //- 2 : CORRECT

0 个答案:

没有答案