使用系統的某些block api(如UIView的block版本寫動畫時),是否也考慮引用循環問題?

系統的某些block api中,UIView的block版本寫動畫時不需要考慮,但也有一些api 需要考慮:

所謂“引用循環”是指雙向的強引用,所以那些“單向的強引用”(block 強引用 self )沒有問題,比如這些:

[UIViewanimateWithDuration:durationanimations:^{ [self.superviewlayoutIfNeeded]; }];

[[NSOperationQueuemainQueue]addOperationWithBlock:^{ self.someProperty= xyz; }];

[[NSNotificationCenterdefaultCenter]addObserverForName:@"someNotification"object:nilqueue:[NSOperationQueuemainQueue]usingBlock:^(NSNotification* notification) {? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? self.someProperty= xyz; }];

這些情況不需要考慮“引用循環”。

但如果你使用一些參數中可能含有 ivar 的系統 api ,如 GCD 、NSNotificationCenter就要小心一點:比如GCD 內部如果引用了 self,而且 GCD 的其他參數是 ivar,則要考慮到循環引用:

__weak__typeof__(self) weakSelf = self;dispatch_group_async(_operationsGroup, _operationsQueue, ^{__typeof__(self) strongSelf = weakSelf;[strongSelfdoSomething];[strongSelfdoSomethingElse];} );

類似的:

__weak__typeof__(self) weakSelf = self;? _observer = [[NSNotificationCenterdefaultCenter]addObserverForName:@"testKey"object:nilqueue:nilusingBlock:^(NSNotification*note) {__typeof__(self) strongSelf = weakSelf;? ? ? [strongSelfdismissModalViewControllerAnimated:YES];? }];

self --> _observer --> block --> self 顯然這也是一個循環引用。

檢測代碼中是否存在循環引用問題,可使用 Facebook 開源的一個檢測工具FBRetainCycleDetector

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容