2012-10-29 25 views
1

我有一個方法需要幾個參數,我需要推遲一部分的方法。我不想將它分成幾種方法並使用[self performSelectorAfterDelay],因爲延遲需要該方法中已有的參數。我需要類似以下的東西iPhone方法的延遲部分

-(void)someMethod{ 
..... 

delay { 

    more code but not a separate self method 
} 
... finish method 
} 

回答

3

dispatch_after功能似乎與你所需要的排隊:

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) { 
    // this code is going to be executed, on the main queue (or thread) after 2.0 seconds. 
}); 

當然,時間可配置,以及它是一個有點混亂,在第一次讀,但一旦你習慣了塊與Objective-C代碼一起工作,你應該很好。謹慎的

一個字:

NEVER,永遠,永遠!使用sleep()阻止iPhone應用程序的主線程。只是不要這樣做!

+0

THX,效果很好,並沒有太多額外的代碼。 – Eric

1

看起來像一個矯枉過正。

-(void)someMethod{ 

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{ 
     NSLog(@"Start code"); 
     dispatch_queue_t backgroundQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0); 
     dispatch_sync(backgroundQueue, ^{ 

      sleep(5); 
      // delayed code 
      NSLog(@"Delayed code"); 
     }); 

     dispatch_sync(backgroundQueue, ^{ 

      // finishing code 
      NSLog(@"Finishing code"); 
     }); 
    }); 

} 

backgroundQueue可能是外部調度呼叫的用戶。它看起來非常糟糕,雖然:)

+0

這不是正確的做法。 GCD已經建立了對延遲的支持,並且試圖跳到另一個隊列並阻止它,以便您可以返回到主隊列似乎沒有意義。 另一個說明 - 這實際上會造成死鎖。 'dispatch_get_global_queue'將返回相同的隊列(如果可以的話),所以在該隊列中使用'sync'會導致應用程序死鎖,這是肯定的。閱讀更多:http://stackoverflow.com/questions/10984732/gcd-why-cant-we-use-a-dispatch-sync-on-the-current-queue –

+0

@Richard J. Ross III我想知道,哪裏你看到要求返回到主隊列嗎?調用隊列可能在後臺,不是嗎? –

+0

讓我把它作爲一個單獨的評論,我試圖用相同的隊列做以下片段:dispatch_sync(backgroundQueue,^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ backgroundQueue,^ { }); });' - 沒有死鎖,你會說什麼? –