2011-03-06 30 views
10

我想稍微延遲地在表視圖上調用setEditing:animated:。通常情況下,我會使用performSelector:withObject:afterDelay:使用performSelector:withObject:afterDelay:使用非對象參數

  1. pSwOaD只接受一個參數
  2. setEditing:animated:第二個參數是一個原始BOOL - 不是一個對象

在過去,我會創建一個虛擬的方法在我自己的班級中,如setTableAnimated,然後致電[self performSelector:@selector(setTableAnimated) withObject:nil afterDelay:0.1f,但對我來說感覺很糟糕。

有沒有更好的方法來做到這一點?

回答

19

爲什麼不使用dispatch_queue?

double delayInSeconds = 2.0; 
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC); 
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){ 
     [tableView setEditing …]; 
    }); 
+0

我不知道爲什麼這是倒票,似乎是一個很好的解決方案給我。 – 2011-03-06 21:31:20

+0

這是一個很好的答案! – 2011-03-06 22:05:43

+0

因爲它需要iOS 4 – Bill 2011-03-06 22:47:46

1

選擇器setEditing:animated:performSelector:withObject:afterDelay不兼容。您只能調用帶有0或1個參數的方法,參數(如果有)必須是一個對象。所以你的解決方法是要走的路。您可以將BOOL值包裝在一個NSValue對象中,並將其傳遞給您的setTableAnimated方法。

16

您需要使用NSInvocation

看到這個代碼,從這個answer取,我已經改變了它略,以配合您的問題:

BOOL yes = YES; 
NSInvocation *inv = [NSInvocation invocationWithMethodSignature:[self.tableView methodSignatureForSelector:@selector(setEditing:Animated:)]]; 
[inv setSelector:@selector(setEditing:Animated:)]; 
[inv setTarget:self.tableView]; 
[inv setArgument:&yes atIndex:2]; //this is the editing BOOL (0 and 1 are explained in the link above) 
[inv setArgument:&yes atIndex:3]; //this is the animated BOOL 
[inv performSelector:@selector(invoke) withObject:nil afterDelay:0.1f]; 
+0

我想用變量名稱一樣'BOOL _yes = YES'是更清晰一點,因爲它減輕了一點混亂,你是否已經有了一個錯字(是VS YES)。 – gabrielk 2014-06-08 18:01:13

+0

也只是想指出,爲'YES'使用變量,而不是直接傳遞bool的原因:'NSInvocation'拋出一個異常:'[NSInvocation setArgument:atIndex:]:NULL地址參數,[解釋這個答案](http://stackoverflow.com/a/11061349/146517)。 – gabrielk 2014-06-08 18:05:17

0

如果你能圍繞它讓你的頭,使用一個NSInvocation抓取器來創建一個調用對象&用1行而不是很多的延遲來調用它:http://overooped.com/post/913725384/nsinvocation

+0

幾乎沒有一條線涉及創建班級。 – 2011-03-06 15:28:50