为什么物体不能被释放?

问题描述:

我有一个块保留周期问题。为什么物体不能被释放?

1.查看演示,redView是一个本地var,只是一种“UIView”,当我弹出secondVC时,但是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不能老是被释放,但secondVC可以释放。为什么?

@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具有参照SecondVC和SecondVC具有参照redView。你应该做weakSelf:

__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's subView? – firmiana

+0

我认为这不重要,它是“局部变量”。它作为self.view的子视图存在于内存中(其中self是您的SecondVC),因此在退出此代码块后不会释放它。 –

+0

是啊,我明白,谢谢你 – firmiana