天天看點

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];

    }];