天天看点

OC的Block中使用weakSelf/strongSelfOC的Block中使用weakSelf/strongSelf

OC的Block中使用weakSelf/strongSelf

在OC的block中如果使用self的话会引起循环引用,也就是说,在block中直接使用self的话会被强引用,解决方案是使用 weakself( __weak __typeof(&*self)weakSelf = self;),这样在block结束释放的时候,weakself因为是弱引用,也会被释放掉。一般情况下是没问题,但是,一下情况会有例外—–
WeakSelf(weakSelf)
    [self myBlock:^(NSString *str) {

        /**
         *  第一次调用的时候weakSelf还没有被释放
         */
        [weakSelf doSomething];


        /**
         *  第二次调用的时候weakSelf有可能就被释放掉了
         */
        [weakSelf doOtherThing];

    }];
           
这个时候就要用到strongSelf啦,如下
WeakSelf(weakSelf)
    [self myBlock:^(NSString *str) {

        /**
         * 在block中需要多次使用weakself时要转成strongSelf,这样确保在block执行完成之前不被释放掉
         */
        __strong __typeof(self) strongSelf = weakSelf;

        [strongSelf doSomething];

        [strongSelf doOtherThing];

    }];