2017-10-11 14 views
-1

私はブロック保持サイクルの質問があります。なぜオブジェクトは解放されないのですか?

1.デモで見ると、redViewはローカルのvarです。私はsecondVCをポップすると「UIView」のようなものですが、secondVCとredViewは解放できません。どうして?

@interface RedView : UIView 
@property(nonatomic,copy) void (^redViewBlock)(); 
@end 

@implementation SecondVC 

- (void)viewDidLoad { 
[super viewDidLoad]; 
self.view.backgroundColor = [UIColor whiteColor]; 

RedView *redView = [[RedView alloc]initWithFrame:CGRectMake(40, 40, 40, 40)]; 
[redView setRedViewBlock:^{ 
    [self aSecondViewFunc]; 
}]; 
[self.view addSubview:redView]; 

} 

-(void)aSecondViewFunc 
{ 
} 

2.IはsecondVCとredView間のグリーンビューを追加し、私はsecondVC、グリーンビューとredViewがリリースさcan`tが、secondVCをリリースすることができポップとき、グリーンビューは、世界的なVARです。どうして?

@interface SecondVC() 

@property(nonatomic,strong)GreenView *greenView; 
@end 

@implementation SecondVC 

- (void)viewDidLoad { 
    [super viewDidLoad]; 
    self.view.backgroundColor = [UIColor whiteColor]; 
    self.greenView = [[GreenView alloc]initWithFrame:CGRectMake(200, 200, 200, 200)]; 
    [self.view addSubview:self.greenView]; 
} 

@implementation GreenView 

-(instancetype)initWithFrame:(CGRect)frame 
{ 
    if (self = [super initWithFrame:frame]) { 
    self.backgroundColor = [UIColor greenColor]; 
    RedView *redView = [[RedView alloc]initWithFrame:CGRectMake(0, 0, 40, 40)]; 
    [redView setRedViewBlock:^{ 
     [self justAFunc]; 
    }]; 
    [self addSubview:redView]; 

    } 
    return self; 
} 

答えて

0

redViewはSecondVCへの参照を有し、SecondVCはredViewへの参照を持っているため。あなたは弱くするべきです。自己:

__weak typeof(self) weakSelf = self; 
RedView *redView = [[RedView alloc]initWithFrame:CGRectMake(40, 40, 40, 40)]; 
[redView setRedViewBlock:^{ 
    [weakSelf aSecondViewFunc]; 
}]; 
[self.view addSubview:redView]; 
+0

しかし、redViewはローカル変数です。もしredViewがSecondVCに追加されていなければ、それはリリース可能です。だから、SecondVCリファレンスのredViewは、redViewがSecondのサブビューなのですから? – firmiana

+0

「ローカル変数」は問題ではないと思います。これはself.viewのサブビューとしてメモリに存在し(selfはあなたのSecondVCです)、このコードブロックの終了後には解放されません。 –

+0

ええ、私は理解して、あなたに感謝します – firmiana

関連する問題