ios – 消息__weak对象?

前端之家收集整理的这篇文章主要介绍了ios – 消息__weak对象?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如果我向弱对象发送消息会怎么样?发送消息是否拥有对象并将其保存在内存中,直到返回?

我在想这个模式:

__weak MyObject *weakSelf = self;
dispatch_async(dispatch_get_main_queue(),^{
    [weakSelf doSomeAction];
});

假设weakSelf在发送消息时不为零,那么在doSomeAction工作时可能会被释放,还是保证在DoSomeAction返回之前保持有效?

解决方法

Clang ARC documentation

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.

消息传递弱引用对变量执行左值对值的转换,这意味着弱引用的值将被保留,然后在当前的完整表达式(基本上是语句)的末尾释放.它基本上等同于分配给一个强变量,其范围仅适用于当前语句,然后发送该强变量.

这里的外卖是如果你想要一个消息一个弱的变量,再也不要再碰到它了,而且在弱参考值最终没有的情况下,你不关心评估方法参数的副作用.继续直接消息弱参考.但是,如果您需要参考弱引用两次(在单独的语句中),或评估参数的副作用是重要的,那么您应该分配一个强变量并在继续之前测试非零.

原文链接:https://www.f2er.com/iOS/337110.html

猜你在找的iOS相关文章