天天看點

IOS 強弱引用問題

在學習AFNetWorking的過程中,經常看到類似: __weak   __typeof ( self )weakSelf =  self ;  然後在block中,看到: __strong   __typeof (weakSelf)strongSelf = weakSelf;

如下代碼:

- (void)setShouldExecuteAsBackgroundTaskWithExpirationHandler:(void (^)(void))handler {

    [self.lock lock];

    if (!self.backgroundTaskIdentifier) {

        UIApplication *application = [UIApplication sharedApplication];

        __weak __typeof(self)weakSelf = self;

        self.backgroundTaskIdentifier = [application beginBackgroundTaskWithExpirationHandler:^{

            __strong __typeof(weakSelf)strongSelf = weakSelf;

            if (handler) {

                handler();

            }

            if (strongSelf) {

                [strongSelf cancel];

                [application endBackgroundTask:strongSelf.backgroundTaskIdentifier];

                strongSelf.backgroundTaskIdentifier = UIBackgroundTaskInvalid;

            }

        }];

    }

    [self.lock unlock];

}

這是因為:沒有添加__strong 引用的話,編譯器會有警告,為什麼會警告呢,因為弱引用的weakself會在某個時間被釋放,有可能是在執行之後的block之前就會被釋放,這樣在後續的操作操作就有可能出錯,是以最好是添加一個對weakSelf的__strong引用。

具體可以參考:

http://stackoverflow.com/questions/11899134/how-to-properly-address-weak-receiver-may-be-unpredictably-null-in-arc-mode

http://stackoverflow.com/questions/19018456/ios-blocks-and-strong-weak-references-to-self