2013-05-01 49 views
1

我試圖創建一個回調,在發生故障延遲後重試該方法。我正在發出此警告:阻止將自身作爲引發編譯器警告的方法的參數

「在此塊中強烈捕獲故障塊可能會導致保留週期。」

typedef void (^MyCallbackBlock)(NSObject *); 

... 

__block MyObject *blockSelf = self; 
__block MyCallbackBlock successBlock = ^(NSObject *someObject) 
{ 
    // To be completed 
}; 
__block MyCallbackBlock failureBlock = ^(NSObject *someObject) 
{ 
    double delayInSeconds = 2.0; 
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC)); 
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){ 
     [blockSelf doSomething:someObject onSuccess:successBlock onFailure:failureBlock]; // <-- Warning is here 
    }); 
}; 
[blockSelf doSomething:someObject onSuccess:successBlock onFailure:failureBlock]; 

... 

- (void)doSomething:(NSObject *)someObject 
      onSuccess:(MyCallbackBlock)successBlock 
      onFailure:(MyCallbackBlock)failureBlock; 

問題:如何使這項工作正常進行?

(我一直在讀通過其他SO問題 - 還沒有找到一個匹配的是,雖然不會感到驚訝,如果一個人在那裏)

+0

這可能是答案,給它一個嘗試:http://stackoverflow.com/questions/7205128/fix-warning-capturing-an-object-strongly-in-this-block-is-likely-to-導致一 – 2013-05-01 20:27:58

回答

0

添加__unsafe_unretained工作,如:

__unsafe_unretained __block MyCallbackBlock successBlock = ^(NSObject *someObject) 
{ 
    // To be completed 
}; 

雖然看起來可能__weak可以工作,在實踐中引起了我的應用程序崩潰。 this answer解釋原因並不是100%清楚,但我想象的是這些。

2

是,該塊需要捕獲本身(以及self)作爲弱參考。

如果您使用ARC *,它應該是這樣的:

MyObject *__weak blockSelf = self; 
__block __weak MyCallbackBlock weakSuccessBlock; 
MyCallbackBlock successBlock = weakSuccessBlock = ^(NSObject *someObject) 
{ 
    // To be completed 
}; 
__block __weak MyCallbackBlock weakFailureBlock; 
MyCallbackBlock failureBlock = weakFailureBlock = ^(NSObject *someObject) 
{ 
    MyCallbackBlock strongSuccessBlock = weakSuccessBlock; 
    MyCallbackBlock strongFailureBlock = weakFailureBlock; 
    double delayInSeconds = 2.0; 
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC)); 
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){ 
     [blockSelf doSomething:someObject onSuccess:strongSuccessBlock onFailure:strongFailureBlock]; 
    }); 
}; 

如果你不使用ARC,更換__block __weak__weak以上只是__block


*:Objective-C中自動引用計數

+0

添加關於ARC的腳註,因爲我不得不穀歌它理解。 – 2013-05-02 06:47:57

+0

__block和__weak的順序是否重要? – 2013-05-02 14:16:21

+1

@BenFlynn:沒有。但'__block'適用於變量,而'__weak'適用於指針類型 – newacct 2013-05-02 19:38:57

相關問題