为了避免保留周期和警告“在此块中强烈捕获自我可能会导致保留周期”,我为我的块中的每个对象添加了类似这样的内容
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"];
};
使用弱引用,保留周期警告会消失,但是如果我在块内引入必须设置的 nnstring,则会出现问题
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"];
weakString=@"atext";
};
这样我收到错误“变量不可分配(缺少_块类型说明符)”,所以我添加了“ _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"];
BlockString=@"atext";
};
以这种方式,一切似乎都正常工作,至少在我进入块内之前......我原来的 Astring 变量是在我的 viewController 的 .h 中定义的,我必须稍后在块外访问它的值,但它是值始终为零。将 @"atext" 分配给 BlockString 不要为我的原始 Astring 变量设置值?我如何设置在我的 viewController 的 .h 中设置的变量的值而不收到警告并且不退出块?