简体   繁体   English

如果我在块内使用ivar,这是一个保留周期吗?

[英]Is it a retain cycle if I use a ivar inside block?

I have some idea about retain cycle. 我对保留周期有一些想法。 If I use self.variable inside block. 如果我使用self.variable内部块。 It is said that I let the view controller retains the block and the block retain the self.property that retain to self. 据说我让视图控制器保留了该块,并且该块保留了对self保留的self.property。 So the retain cycle occurs.However ,if I declare a instance variable , and I use it inside the block , is it a retain cycle? 因此发生了保留周期。但是,如果我声明一个实例变量,并在块中使用它,它是否是一个保留周期? If YES, how to solve the problem? 如果是,该如何解决?

The code is : 代码是:

@interface ViewController (){
    NSString *phone;
}
@end
-(void)example
{

    [self.varble ^block
     {
         phone=@"abc";// a retain cycle?
     }];

}

Yes that will still retain self 是的,那仍然会保留自我

You should either reference the ivar through a weak instance: 您应该通过一个弱实例来引用ivar:

@interface ViewController (){
    NSString *phone;
}
@end
-(void)example
{
    __weak typeof(self) weakSelf = self;
    [self.varble ^block
     {
         typeof(self) self = weakSelf;
         self->phone=@"abc";// a retain cycle?
     }];

}

Or if you weren't changing the value (just simply using it), copy the value of the ivar into a local variable: 或者,如果您没有更改值(只是简单地使用它),请将ivar的值复制到局部变量中:

@interface ViewController (){
    NSString *phone;
}
@end
-(void)example
{
    NSString *phoneValue = [phone copy]; // the copy is optional, but good practice
    [self.varble ^block
     {
         [phoneValue someMethod];
     }];

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM