将对象传递到块是否可以保证保留其生命周期? [英] Does a passing of an object to a block guarantee that its lifecycle will be retained?

查看:114
本文介绍了将对象传递到块是否可以保证保留其生命周期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我具有以下typedef:

Let's assume I have the following typedef:

typedef void (^myBlock)(id);

我有一些方法 myMethod 接受 myBlock 作为参数,并为其生成一些 id 变量:

And I have some method myMethod accepting myBlock as an argument and yielding some id variable to it:

void myMethod(id myObj, myBlock block) {
    // ...
    block(myObj);
    // ...
}

所以,如果我有以下内容:

So if I have the following:

- (void) someMethod {
    __block id myObj; // Some initialization local to the scope of someMethod;
    // myObj = ... some assignment to myObj so it is not nil...

    dispatch_async(someQueue(), ^{
        // (*) Some long, possibly multi-queued and multi-blocked, processing, 
        // so we are sure that someMethod will run out:
        // ...

        // 1. Can I be sure that myObj is still alive and actual here 
        // after the long processing (*)?

        myMethod(myObj, ^(id myObj) {
            // (**) Some long, possibly multi-queued, processing here too...

            // 2. Can I be sure that myObj is still alive and actual here 
            // after the long processing (**) finishes?
        })
    })
}

我是否必须特别保留myObj ,以便它可以存在于不同的队列/块中?

do I have to specially retain myObj so it would live across different queues/blocks?

很抱歉,如果我要问的是显而易见的东西,并且有足够的文献记录,那时候我才刚刚开始学习Objective-C,当时ARC很可能是默认值,因此它不需要我在意这些保留计数,自动发布和其他东西,只在我在这里描述的情况下考虑它们.

Sorry if I'm asking something obvious and enough documented - I've just started learning Objective-C in the time, when ARC is likely a default so it does not require me to care much about these retain counts, autoreleases and other stuff, and think about them only in the situations like I described here.

推荐答案

  1. 经过长时间的处理(*),我可以确定myObj在这里仍然有效吗?

是的,即使您没有使用块说明符,因为块内的块保留了它.

Yes, and even if you weren't using the block specifier because the block inside the block retains it.

  1. 我可以确定经过长时间处理(**)后,myObj仍在运行且仍在此处吗?

是的.ARC中保留了块中使用的每个变量.

Yes.Every variable used inside a block is retained by ARC.

PS:所有这些都通过ARC.

PS: All this with ARC.

这篇关于将对象传递到块是否可以保证保留其生命周期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆