self 会保留在块内吗?

发布于 2024-12-21 14:56:16 字数 532 浏览 1 评论 0原文

在调用该块之前/之后,retaincount 始终为 1。 来自 apple block doc 我们知道 self 应该保留。谁能知道为什么吗?

NSLog(@"Before block retain count: %d", [self retainCount]);    
void (^block)(void) = ^(void){
    UIImage* img = [UIImage imageNamed:@"hometown.png"];
    [self setImage:img];
    NSLog(@"After block retain count: %d", [self retainCount]);
};
block();

Before/After call the block, the retaincount is always 1.
From apple block doc we know that the self should retain. Can anyone know why?

NSLog(@"Before block retain count: %d", [self retainCount]);    
void (^block)(void) = ^(void){
    UIImage* img = [UIImage imageNamed:@"hometown.png"];
    [self setImage:img];
    NSLog(@"After block retain count: %d", [self retainCount]);
};
block();

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

壹場煙雨 2024-12-28 14:56:16

首先,retainCount没有用。不要调用它。。

复制块时,块仅保留捕获的对象。因此,在该示例中,self 不会被块保留。

First, retainCount is useless. Don't call it..

Blocks only retain captured objects when the block is copied. Thus, self won't be retained by the block in that example.

忘东忘西忘不掉你 2024-12-28 14:56:16

好吧,我做了一些研究,现在事情变得更加清楚了。首先,我没有在block1上使用@property,这意味着当我设置它时,没有复制任何内容,因此它们不会被保留,其次,如果我们执行[块复制],如果我们不复制,变量将被保留,该块指向一个堆栈地址,将其复制到堆以使其安全。

变量'array'是一个成员变量,所以它不被保留,同时self也会被保留,无论你是否把它放在块中,如果该变量是局部变量,它都会被保留。 (这是我仍然困惑的事情,为什么成员变量没有保留,而是在保留计数上添加了一个self???请回答我?)

使用块后我们可以将其设置为nil self.block = 零;使变量被释放,并避免循环引用。

附言。打破保留循环的方法是使用 __block idweakSelf = self;在块中,所以这意味着 __block 变量也不会被保留。

OK I did some research, now things became more clear. firstly, I didn't use @property on block1, which means when I set it, nothing is copied, so they are not retained, secondly, if we do a [block copy], the variables will be retained, if we dont copy, the block points to a stack address, copy it to heap to make it safe.

the variable 'array' is a Member variable, so it's not retained and meanwhile the self will be retained, whether you put it in the block or not, if the variable is a local variable, it will be retained. ( this is the thing that Im still confused abt, why the member variable is not retained,instead the self is added one more on retain count??? pls answer me?)

after using the block we could set it to nil self.block = nil; to make variables released, and avoid the retain cycle.

PS. a method to break retain cycle is use __block id weakSelf = self; in the block, so it means __block variables are also not retained.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文