gpt4 book ai didi

ios - Objective-C ARC block __strong __weak

转载 作者:行者123 更新时间:2023-11-28 21:35:23 24 4
gpt4 key购买 nike

有圆弧

测试1:

@interface test01ViewController ()

@property (strong) void(^myBlock)(id obj, NSUInteger idx, BOOL stop);

@end

@implementation test01ViewController

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
self.navigationItem.title = @"test01";

[self setMyBlock:^(id obj, NSUInteger idx, BOOL stop) {
[self doSomethingWithObj:obj];
}];
}

object (self) 具有对该 block 的显式强引用。并且该 block 具有对 self 的隐式 strong 引用。这是一个循环,现在两个对象都不会被正确释放。

所以 test1 dealloc 没有调用。

测试2:

@interface test03ViewController ()

@property (strong) void(^myBlock)(id obj, NSUInteger idx, BOOL stop);

@end

@implementation test03ViewController

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.

self.navigationItem.title = @"test03";

__weak test03ViewController *weakSelf = self;
[self setMyBlock:^(id obj, NSUInteger idx, BOOL stop) {
__strong test03ViewController *strongSelf = weakSelf;
[strongSelf doSomethingWithObj:obj];
}];
}

__weakSelf -> __strongSelf,我觉得跟test1没有区别,但是test2可以调用dealloc

为什么?

最佳答案

看看这个答案:https://stackoverflow.com/a/28475562/543224

Anyway regarding this pattern, capturing a strong reference there doesn't do anything for the case of self getting deallocated before the block runs, that can still happen. It does ensure self doesn't get deallocated while executing the block. This matters if the block does async operations itself giving a window for that to happen.

关于ios - Objective-C ARC block __strong __weak,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34119424/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com