在實現API時,如何避免在塊中捕獲self?我有一個工作的應用程序,我正在努力將其轉換為Xcode 4.2中的ARC。其中一個預檢警告涉及self強烈捕獲導致保留周期的塊。我已經制作了一個簡單的代碼示例來說明問題。我相信我理解這意味著什么,但我不確定實現這種情況的“正確”或推薦方法。self是MyAPI類的一個實例下面的代碼被簡化為僅顯示與我的問題相關的對象和塊的交互假設MyAPI從遠程源獲取數據,MyDataProcessor處理該數據并生成輸出處理器配置有塊以通信進度和狀態代碼示例:// code sampleself.delegate = aDelegate;self.dataProcessor = [[MyDataProcessor alloc] init];self.dataProcessor.progress = ^(CGFloat percentComplete) { [self.delegate myAPI:self isProcessingWithProgress:percentComplete];};self.dataProcessor.completion = ^{ [self.delegate myAPIDidFinish:self]; self.dataProcessor = nil;};// start the processor - processing happens asynchronously and the processor is released in the completion block[self.dataProcessor startProcessing];問題:我在做什么“錯誤”和/或如何修改它以符合ARC慣例?
3 回答
慕姐4208626
TA貢獻1852條經驗 獲得超7個贊
當您肯定將來會破壞循環時,還可以選擇禁止警告:
#pragma clang diagnostic push#pragma clang diagnostic ignored "-Warc-retain-cycles"self.progressBlock = ^(CGFloat percentComplete) {
[self.delegate processingWithProgress:percentComplete];}#pragma clang diagnostic pop這樣你就不必四處尋找__weak,self別名和明確的ivar前綴。
叮當貓咪
TA貢獻1776條經驗 獲得超12個贊
對于常見的解決方案,我在預編譯頭中定義了這些。避免捕獲并仍然通過避免使用來啟用編譯器幫助id
#define BlockWeakObject(o) __typeof(o) __weak#define BlockWeakSelf BlockWeakObject(self)
然后在代碼中你可以做:
BlockWeakSelf weakSelf = self;self.dataProcessor.completion = ^{
[weakSelf.delegate myAPIDidFinish:weakSelf];
weakSelf.dataProcessor = nil;};- 3 回答
- 0 關注
- 513 瀏覽
添加回答
舉報
0/150
提交
取消
