block引用之间有什么区别

block引用之间有什么区别

本文介绍了__weak和__block引用之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读Xcode的文档,这使我感到困惑:

I'm reading Xcode's documentation, and here is something that puzzles me:

__block typeof(self) tmpSelf = self;
[self methodThatTakesABlock:^ {
    [tmpSelf doSomething];
}];

以下内容是从文档中复制的:

The following is copied from the documentation:

我不明白弱者(或__block)"是什么意思?

I don't understand what does 'a weak (or __block)' mean?

__block typeof(self) tmpSelf = self;

__weak typeof(self) tmpSelf = self;

这里完全一样吗?

我在文档中发现了另外一块:

I found another piece in the document:

所以,我完全感到困惑.

So, I'm totally puzzled.

推荐答案

来自有关__block的文档

From the docs about __block

来自有关__weak

From the docs about __weak

因此,它们在技术上是不同的. __block用于阻止将变量从外部作用域复制到块作用域. __weak是一个自定界的弱指针.

So they are technically different things. __block is to stop your variable being copied from your external scope into your block scope. __weak is a self delimiting weak pointer.

请注意,我从技术上说过,因为对于您的情况,他们将(几乎)做同样的事情.唯一的区别是您是否使用ARC.如果您的项目使用ARC,并且仅适用于iOS4.3及更高版本,请使用__weak.如果以某种方式释放了全局范围引用,它可以确保将引用设置为nil.如果您的项目不使用ARC或用于较早的OS版本,请使用__block.

Note I said technically, because for your case they will do (almost) the same thing. The only difference is if you are using ARC or not. If your project uses ARC and is only for iOS4.3 and above, use __weak. It ensures the reference is set to nil if the global scope reference is releases somehow. If your project doesn't use ARC or is for older OS versions, use __block.

这里有一个细微的差别,请确保您理解它.

There is a subtle difference here, make sure you understand it.

另一个难题是__unsafe_unretained.此修饰符与__weak几乎相同,但适用于4.3之前的运行时环境.但是,它没有设置为nil,可能会导致指针悬空.

Another piece to the puzzle is __unsafe_unretained. This modifier is almost the same as __weak but for pre 4.3 runtime environments. HOWEVER, it is not set to nil and can leave you with hanging pointers.

这篇关于__weak和__block引用之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 17:42