2013-09-27 61 views
2

为了避免保留周期和警告“在此块强烈捕捉自我很可能会导致保留周期”我在我的块中添加一些为每个对象这样无__block变量设置一个NSString的

MyViewController *__weak weakSelf= self; 
NSMutableArray *__weak weakArray=AnArray; 
UILabel *__weak weakLabel=ALabel; 

///the block code with some examples 
up2.completionBlock = ^(NSDictionary *headers, NSString *responseString) { 

     [weakSelf aMethodInTheController]; 
     [weakLabel setHidden:NO]; 
     [weakArray addObject:@"something"]; 

}; 

与弱引用保留周期警告消失了,但是有,如果我的块中引入了必须设置好的

MyViewController *__weak weakSelf= self; 
NSMutableArray *__weak weakArray=AnArray; 
UILabel *__weak weakLabel=ALabel; 

NSString *__weak weakString=AString; 

///the block code with some examples 
up2.completionBlock = ^(NSDictionary *headers, NSString *responseString) { 

    [weakSelf aMethodInTheController]; 
    [weakLabel setHidden:NO]; 
    [weakArray addObject:@"something"]; 
    [email protected]"atext"; 

}; 

这样,我又收到错误nnstring问题“变量不分配(失踪_ 块类型指定IER)”,所以我必须添加‘ _block’

MyViewController *__weak weakSelf= self; 
NSMutableArray *__weak weakArray=AnArray; 
UILabel *__weak weakLabel=ALabel; 

NSString *__weak weakString=AString; 
__block NSString *BlockString = weakString;  

///the block code with some examples 
up2.completionBlock = ^(NSDictionary *headers, NSString *responseString) { 

[weakSelf aMethodInTheController]; 
[weakLabel setHidden:NO]; 
[weakArray addObject:@"something"]; 
[email protected]"atext"; 

}; 

这样一切似乎正常工作,至少要等到我是块里面......我原来ASTRING变量在.H定义我的viewController,我不得不访问它的价值之后和块外,但它的价值永远是零。将@“atext”分配给BlockString不要为我的原始Astring变量设置一个值?我怎么能设置一个变量的值设置在我的viewController的.h没有收到警告和没有退出块?

回答

2

指定@"atext"到​​不要设置一个值到我原来的Astring变量吗?

不,它不设置Astring,它不应该设置它:当你做这个

NSString *__weak weakString=AString; 

创建第二个引用(恰好是__weak)被引用的对象在AString变量(比如,它的@"some-text"):

Before

当您设置weakString INSI德块到@"atext",你再点所指的是一个不同的对象,但@"some-text"对象仍然由AString变量引用:

After

如果你想改变AString变量,将它设置你的块内。如果是伊娃,请使用weakSelf->AString。如果是本地,则在其声明中添加__block

1

假设aLabelanArray是视图控制器的ivars,你真的只是担心weakSelf,然后从那里引用任何ivars和属性。而且,由于您有效地解除了引用ivars的作用,因此您可以在该块内部引用强引用(因为您无法解引用弱变量)。因此,假设aLabelanArray,一个aString是高德:

MyViewController *__weak weakSelf = self; 

///the block code with some examples 
up2.completionBlock = ^(NSDictionary *headers, NSString *responseString) { 

    MyViewController *strongSelf = weakSelf; 
    if (strongSelf) { 
     [strongSelf aMethodInTheController]; 
     [strongSelf->aLabel setHidden:NO]; 
     [strongSelf->anArray addObject:@"something"]; 
     strongSelf->aString = @"something else"; 
    } 
}; 

坦率地说,我不提领高德的粉丝,我宁愿使用(有许多原因)性能。但都工作。

有关此模式的示例,请参阅Transitioning To ARC Release Notes的“使用寿命限定符以避免强参考周期”部分(特别是稍后讨论“非平凡周期”的部分)。