如何定义此方法以不阻止主线程?
解决方法 除非您特别需要计时器,否则您可以使用Grand Central dispatch.以下代码段将在默认优先级并发队列(即后台线程)上2秒后执行一个块.如果您认为合适,可以更改队列的优先级,但除非您在并发队列上处理大量不同的 *** 作,否则默认就足够了.
double delayInSeconds = 2.0;dispatch_time_t popTime = dispatch_time(disPATCH_TIME_Now,(int64_t)(delayInSeconds * NSEC_PER_SEC));dispatch_after(popTime,dispatch_get_global_queue(disPATCH_QUEUE_PRIORITY_DEFAulT,0),^(voID){ // Your code here});
如果您想重复调用它,则可以使用dispatch_source_set_timer设置重复执行.它的主旨如下:
// Create a dispatch source that'll act as a timer on the concurrent queue// You'll need to store this somewhere so you can suspend and remove it later ondispatch_source_t dispatchSource = dispatch_source_create(disPATCH_SOURCE_TYPE_TIMER,0)); // Setup params for creation of a recurring timerdouble interval = 2.0;dispatch_time_t startTime = dispatch_time(disPATCH_TIME_Now,0);uint64_t intervalTime = (int64_t)(interval * NSEC_PER_SEC);dispatch_source_set_timer(dispatchSource,startTime,intervalTime,0);// Attach the block you want to run on the timer firedispatch_source_set_event_handler(dispatchSource,^{ // Your code here});// Start the timerdispatch_resume(dispatchSource);// ----// When you want to stop the timer,you need to suspend the sourcedispatch_suspend(dispatchSource);// If on iOS5 and/or using MRC,you'll need to release the source toodispatch_release(dispatchSource);总结
以上是内存溢出为你收集整理的ios – 在Objective – C中的另一个线程中的计时器全部内容,希望文章能够帮你解决ios – 在Objective – C中的另一个线程中的计时器所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)