传递一个__weak对象? [英] Messaging a __weak object?
问题描述
如果我向弱对象发送消息会怎样?发送消息是否拥有该对象并将其保留在内存中直到返回?
What happens if I send a message to a weak object? Does sending the message possess the object and hold it in memory until return?
我正在考虑这种模式:
__weak MyObject *weakSelf = self;
dispatch_async(dispatch_get_main_queue(), ^{
[weakSelf doSomeAction];
});
假设 weakSelf
是非零的消息被发送,可能在 doSomeAction
工作时被解除分配,或者保证在 doSomeAction
返回之前保持有效?
Assuming weakSelf
is non-nil when the message is sent, might it be deallocated while doSomeAction
is working or is it guaranteed to remain valid until doSomeAction
returns?
推荐答案
来自 Clang ARC文档:
阅读 在对象左值上执行左值到右值转换时发生。
Reading occurs when performing a lvalue-to-rvalue conversion on an object lvalue.
- 对于
__弱
对象,保留当前的指针,然后在当前的完整表达式结束时释放。这必须相对于赋值和指针的最终版本以原子方式执行。
- For
__weak
objects, the current pointee is retained and then released at the end of the current full-expression. This must execute atomically with respect to assignments and to the final release of the pointee.
消息传递a弱引用对变量执行左值到右值的转换,这意味着弱引用的值将被保留,然后在当前的完整表达式(基本上是语句)结束时释放。它基本上等同于分配一个强变量,其范围仅适用于当前语句,然后传递该强变量。
Messaging a weak reference performs an lvalue-to-rvalue conversion on the variable, which means the value of the weak reference will be retained and then released at the end of the current full-expression (basically, the statement). It's basically equivalent to assigning to a strong variable whose scope only lasts for the current statement, and then messaging that strong variable.
这里的内容是如果您想要发送消息a弱变量一次,永远不要再触摸它,你不关心在弱引用结束的情况下评估方法参数的副作用 nil
,然后继续直接向弱引用发送消息。但是如果你需要两次引用弱引用(在单独的语句中),或者评估参数的副作用很重要,那么你应该分配一个强变量并测试非 - nil
继续之前。
The takeaway here is if you want to message a weak variable once, and never touch it again, and you don't care about the side-effects of evaluating the arguments to the method in the case where the weak reference ends up nil
, then go ahead and message the weak reference directly. But if you need to refer to the weak reference twice (in separate statements), or the side-effects of evaluating the arguments do matter, then you should assign to a strong variable and test for non-nil
before proceeding.
这篇关于传递一个__weak对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!