iPhone-SDK:在后台调用一个函数? [英] iPhone-SDK:Call a function in the background?
问题描述
是否可以在iPhone SDK开发中以编程方式在一定时间间隔后在后台调用我的函数?我希望在我的应用程序运行期间在后台调用一个特定功能一定的时间间隔(可能每10分钟)..
Is it possible to call my function in the background after certain interval programmatically in iPhone SDK development? I want to call one particular function in the background for certain time intervals(may be every 10 mins) during my app in on running..
你能分享一下你的想法吗? 。
Could you please share your ideas.
谢谢。
Clave /
推荐答案
最简单的方法是在主线程run-loop上安排 NSTimer
。我建议在您的应用程序委托上实现以下代码,并从 applicationDidFinishLaunching:
调用 setupTimer
。
Easiest way is to schedule a NSTimer
on the main threads run-loop. I suggest that the following code is implemented on your application delegate, and that you call setupTimer
from applicationDidFinishLaunching:
.
-(void)setupTimer;
{
NSTimer* timer = [NSTimer timerWithTimeInterval:10 * 60
target:self
selector:@selector(triggerTimer:)
userInfo:nil
repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
}
-(void)triggerTimer:(NSTimer*)timer;
{
// Do your stuff
}
如果你的东西这里需要很长时间,你无法阻止主线程然后使用以下方式调用你的东西:
If your stuff here takes a long time, and you can not hold up the main thread then either call your stuff using:
[self performSelectorInBackground:@selector(myStuff) withObject:nil];
或者你可以运行 NSTimer
背景线程用这样的东西(我故意泄漏线程对象):
Or you could run the NSTimer
on a background thread by with something like this (I am intentionally leaking the thread object):
-(void)startTimerThread;
{
NSThread* thread = [[NSThread alloc] initWithTarget:self
selector:@selector(setupTimerThread)
withObject:nil];
[thread start];
}
-(void)setupTimerThread;
{
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
NSTimer* timer = [NSTimer timerWithTimeInterval:10 * 60
target:self
selector:@selector(triggerTimer:)
userInfo:nil
repeats:YES];
NSRunLoop* runLoop = [NSRunLoop currentRunLoop];
[runLoop addTimer:timer forModes:NSRunLoopCommonModes];
[runLoop run];
[pool release];
}
-(void)triggerTimer:(NSTimer*)timer;
{
// Do your stuff
}
这篇关于iPhone-SDK:在后台调用一个函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!