为什么对象不能被释放?

时间:2017-10-11 09:40:20

标签: ios objective-c

我有一个块保留周期问题。

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.我在secondVC和redView之间添加了一个greenView,greenView是一个全局var,当我弹出secondVC时,greenView和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;
}

1 个答案:

答案 0 :(得分: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];