0

这是我学到的:使用self保留块时

  1. 我需要一个weakSelf打破保留周期
  2. 我需要一个strongSelf来防止self中途变成零

所以我想测试 a 是否strongSelf真的可以self像这样保持活力:

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    NSLog(@"viewDidLoad");
    self.test = @"test";
    NSLog(@"%@",self.test);
    __weak typeof(self)weakSelf = self;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        __strong typeof(weakSelf)strongSelf = weakSelf;
        strongSelf.test = @"newTest";
        NSLog(@"%@",strongSelf.test);
    });
}

- (void)dealloc {
    NSLog(@"dealloc");
}

@end

ViewController 将被推入一个 navigationController 并立即弹出。输出是

样本

为什么是空的?

还有另一个问题,我有一个项目,其中包含大量weakSelf没有的项目,strongSelf并且我收到大量信号 11 崩溃。有关系吗?值得添加strongSelf到它们中吗?

4

3 回答 3

1

strongSelf ensures that if self was not released yet, it won't during the execution of the block.

If the self is gone before you create strongSelf, it will be nil.

You should check, if strongSelf does contain something:

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    typeof(weakSelf)strongSelf = weakSelf; // __strong is not needed
    if(strongSelf){
        strongSelf.test = @"newTest";
        NSLog(@"%@",strongSelf.test);
    }
});
于 2015-03-17T07:49:10.790 回答
0

The code in your block is executed after 3s delay. So by this time the weakSelf is already nil. That's why strongSelf is nil

于 2015-03-17T07:49:48.680 回答
0

我认为您没有正确解决问题。使用 weakself 将打破保留周期,但是这一行:

__strong typeof(weakSelf)strongSelf = weakSelf;

在执行块之前不会捕获对自身的强引用。因此,如果您在块外指向 VC 的指针为 nil,则 VC 将被释放,并且当您击中块时,weakSelf 将为零 - 这意味着您的 strongSelf 也将为零。仅捕获强引用保证如果您在块的开头有弱自我,您将拥有它直到结束并且它不会同时被释放。但是,如果在块开始时 weakSelf 为 nil - strongSelf 也将为 nil。此外,您不需要在块内将其声明为强,因为根据定义它将是强的,因此可以将其替换为:

typeof(weakSelf)strongSelf = weakSelf;

或者

id strongSelf = weakSelf;
于 2015-03-17T07:51:19.330 回答