Ios 块中具有强引用的弱变量:不创建保留循环?

Ios 块中具有强引用的弱变量:不创建保留循环?,ios,objective-c,retain-cycle,Ios,Objective C,Retain Cycle,当我们在块内将弱引用传递给强引用时,它为什么会起作用?如果一个块中的局部变量被保留,这应该给self添加一个保留,从而造成这个错误的保留周期 以下是一个例子: __weak id weakSelf = self; [self.operationQueue addOperationWithBlock:^{ NSNumber* result = findLargestMersennePrime(); [[NSOperationQueue mainQueue] addOperatio

当我们在块内将弱引用传递给强引用时,它为什么会起作用?如果一个块中的局部变量被保留,这应该给
self
添加一个保留,从而造成这个错误的保留周期

以下是一个例子:

__weak id weakSelf = self; 
[self.operationQueue addOperationWithBlock:^{
    NSNumber* result = findLargestMersennePrime();
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{ 
        MyClass* strongSelf = weakSelf; 
        strongSelf.textLabel.text = [result stringValue];
    }]; 
}];

不,它不会创建一个循环,因为self没有被捕获为强大的!:)


strongSelf是一个保留self的强引用,但由于strongSelf是一个本地变量,因此当块完成且保留计数下降时,它会被释放,不会产生循环,因为self没有被捕获为强变量:)


strongSelf是一个保留self的强引用,但由于strongSelf是一个本地变量,因此在创建或复制块时,它会被释放,并且保留计数会下降到精细值(例如,当您将其计划到gcd时,它可以被复制),引用的变量会被捕获(除非使用u块说明符声明)。保留强引用,不保留弱引用

当您创建本地
strongSelf
变量时,当块执行时,它保持
self
活动(即当它未执行且位于属性中时,没有强引用)。当您直接引用
self
时-
self
被捕获并保留,现在它在块处于活动状态时保持
self

__weak id weakSelf = self; 
[self.operationQueue addOperationWithBlock:^{
    NSNumber* result = findLargestMersennePrime();
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{ 

        MyClass* strongSelf = weakSelf; // strong reference when block executes
        [self foo]; // strong reference when block created/copied

        strongSelf.textLabel.text = [result stringValue];
    }]; 
}];

看到区别了吗?如果使用直接
self
引用终止指向对象的所有强指针,则块内仍有一个强引用,即捕获并保留的强引用。同时,当执行块时,本地
strongSelf
指针只对
self
进行强引用,因此,如果
self
已经死了,
weakSelf
将为零,
strongSelf
将获得零值。

<(例如,当您将其调度到gcd时,可以复制它),捕获引用的变量(除非使用_块说明符声明)。保留强引用,不保留弱引用

创建本地
strongSelf
变量时,当块执行时,它保持
self
活动(即,当它未执行且位于属性中时,没有强引用)。当您直接引用
self
时-
self
被捕获并保留,现在它保持
self
,而块处于活动状态

__weak id weakSelf = self; 
[self.operationQueue addOperationWithBlock:^{
    NSNumber* result = findLargestMersennePrime();
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{ 

        MyClass* strongSelf = weakSelf; // strong reference when block executes
        [self foo]; // strong reference when block created/copied

        strongSelf.textLabel.text = [result stringValue];
    }]; 
}];
看到区别了吗?如果您使用直接
self
引用杀死所有指向对象的强指针,那么块内仍然有一个强引用,即捕获并保留的强引用。同时,在执行块时,本地
strongSelf
指针仅保留对
self
的强引用,因此,如果
self
已死亡,
weakSelf
将为零,
strongSelf
将获得零值