weakSelf(好的)、strongSelf(坏的)和 blocks(丑的)

weakSelf (the good), strongSelf (the bad) and blocks (the ugly)

我读过当这样的块被执行时:

__weak typeof(self) weakSelf = self;
[self doSomethingInBackgroundWithBlock:^{
        [weakSelf doSomethingInBlock];
        // weakSelf could possibly be nil before reaching this point
        [weakSelf doSomethingElseInBlock];
}]; 

应该这样做:

__weak typeof(self) weakSelf = self;
[self doSomethingInBackgroundWithBlock:^{
    __strong typeof(weakSelf) strongSelf = weakSelf;
    if (strongSelf) {
        [strongSelf doSomethingInBlock];
        [strongSelf doSomethingElseInBlock];
    }
}];

所以我想复制 weakSelf 在块执行过程中变为 nil 的情况。

所以我创建了以下代码:

* ViewController *

@interface ViewController ()

@property (strong, nonatomic) MyBlockContainer* blockContainer;
@end

@implementation ViewController

- (IBAction)caseB:(id)sender {
    self.blockContainer = [[MyBlockContainer alloc] init];
    [self.blockContainer createBlockWeakyfy];
    [self performBlock];
}


- (IBAction)caseC:(id)sender {
    self.blockContainer = [[MyBlockContainer alloc] init];
    [self.blockContainer createBlockStrongify];
    [self performBlock];
}


- (void) performBlock{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        self.blockContainer.myBlock();
    });
    [NSThread sleepForTimeInterval:1.0f];
    self.blockContainer = nil;
    NSLog(@"Block container reference set to nil");
}
@end

* MyBlockContainer *

@interface MyBlockContainer : NSObject

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

- (void) createBlockWeakyfy;
- (void) createBlockStrongify;

@end

@implementation MyBlockContainer

- (void) dealloc{
    NSLog(@"Block Container Ey I have been dealloc!");
}

- (void) createBlockWeakyfy{
    __weak __typeof__(self) weakSelf = self;
    [self setMyBlock:^() {
        [weakSelf sayHello];
        [NSThread sleepForTimeInterval:5.0f];
        [weakSelf sayGoodbye];
    }];
}

- (void) createBlockStrongify{

    __weak __typeof__(self) weakSelf = self;
    [self setMyBlock:^() {
        __typeof__(self) strongSelf = weakSelf;
        if ( strongSelf ){
            [strongSelf sayHello];
            [NSThread sleepForTimeInterval:5.0f];
            [strongSelf sayGoodbye];
        }
    }];
}

- (void) sayHello{
    NSLog(@"HELLO!!!");
}

- (void) sayGoodbye{
    NSLog(@"BYE!!!");
}


@end

所以我期待 createBlockWeakyfy 会生成我想复制的场景,但我没能做到。

createBlockWeakyfy 和 createBlockStrongify 的输出相同

HELLO!!!
Block container reference set to nil 
BYE!!!
Block Container Ey I have been dealloc!

有人可以告诉我我做错了什么吗?

您的 dispatch_async 块是一个创建强大的参考。当该块访问您的 MyBlockContainer 以获取其 myBlock 属性 时,它会在该块的生命周期内创建对它的强引用。

如果您将代码更改为:

 __weak void (^block)() = self.blockContainer.myBlock;

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    block();
});

您应该会看到预期的结果。