ios – weakSelf(好),strongSelf(坏)和块(丑陋)

前端之家收集整理的这篇文章主要介绍了ios – weakSelf(好),strongSelf(坏)和块(丑陋)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我已经读过当执行这样的块时:
__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,^{
    block();
});

你应该看到你期待的结果.

原文链接:https://www.f2er.com/iOS/334110.html

猜你在找的iOS相关文章