引用块内的实例变量 [英] Reference to instance variables inside a block

查看:86
本文介绍了引用块内的实例变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个课程(非ARC环境):

Suppose I have a class (non-ARC environment):

@interface SomeObject : NSObject {
    UILabel *someLabel;
    dispatch_queue_t queue;
}
- (void)doAsyncStuff;
- (void)doAnimation;
@end

@implementation SomeObject

- (id)init {
    self = [super init];
    if (self) {
        someLabel = [[UILabel alloc] init];
        someLabel.text = @"Just inited";
        queue = dispatch_queue_create("com.me.myqueue", DISPATCH_QUEUE_SERIAL);
    }
    return self;
}

- (void)doAsyncStuff {
    dispatch_async(queue, ^{
        ...
        // Do some stuff on the current thread, might take a while
        ...
        dispatch_async(dispatch_get_main_queue(), ^{
            someLabel.text = [text stringByAppendingString:@" in block"];
            [self doAnimation];
        }
    }
}

- (void)doAnimation {
    ...
    // Does some animation in the UI
    ...
}

- (void)dealloc {
    if (queue) {
        dispatch_release(queue);
    }
    [someLabel release];
    [super dealloc];
}

如果我的代码块开始执行,然后所有其他对此对象实例的引用都释放了它,那么我保证不会调用dealloc,因为嵌套的代码块引用了实例变量(并且引用了self)- -嵌套块退出后会发生dealloc吗?我的理解是,我的街区对自我有很强的借鉴意义,因此应该是犹太洁食.

If my block gets kicked off and then everything else holding a reference to the instance of this object releases it, am I guaranteed that dealloc won't be called because the nested block refers to an instance variable (and to self) -- that dealloc will happen after the nested block exits? My understanding is that my block has a strong reference to self, so this should be kosher.

推荐答案

基于您所说的原因,这很好.

This is fine, for the reasons you've stated.

要注意的重要一点是,如果类(用self表示)以任何方式保留了该块,则将创建一个保留周期.因为您正在内联定义它,并将其传递给dispatch_async,所以您应该没事.

The important thing to note is that you would create a retain cycle, if the class (represented by self) retained the block in any way. Because you're defining it in-line, and passing it to dispatch_async, you should be ok.

这篇关于引用块内的实例变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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