-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;
}
しかし、redViewはローカル変数です。もしredViewがSecondVCに追加されていなければ、それはリリース可能です。だから、SecondVCリファレンスのredViewは、redViewがSecondのサブビューなのですから? – firmiana
「ローカル変数」は問題ではないと思います。これはself.viewのサブビューとしてメモリに存在し(selfはあなたのSecondVCです)、このコードブロックの終了後には解放されません。 –
ええ、私は理解して、あなたに感謝します – firmiana