__weak __typeof(self) weakSelf = self 和__strong __typeof(self) strongSelf = self

本文探讨了如何在Objective-C中通过使用NSOperationQueue来避免对象间的循环引用导致的内存泄漏问题,重点介绍了如何将操作块传递给队列,从而使得对象在任务完成后自动被释放。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 What you want to avoid with blocks is a retain cycle—two objects keeping each other alive unnecessarily.

If I have an object with this property:

@property (strong) void(^completionBlock)(void);

and I have this method:

- (void)doSomething
{
    self.completionBlock = ^{
        [self cleanUp];
    };

    [self doLongRunningTask];
}

the block will be kept alive when I store it in the completionBlock property. But since it references self inside the block, the block will keep self alive until it goes away—but this won’t happen since they’re both referencing each other.

In this method:

- (void)doSomething
{
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
        [self cleanUp];
    }];

    [self doLongRunningTask];
}

you don’t need to make a weak reference to self. The block will keep self alive, since it references self from within, but since all we’re doing is handing the block off to [NSOperationQueue mainQueue]self isn’t keeping the block alive.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值