4 iphone
是否可以在iPhone SDK开发中以编程方式在一定时间间隔后在后台调用我的函数?我希望在我的应用程序运行期间在后台调用一个特定的功能一定时间间隔(可能每10分钟).
你能分享一下你的想法吗?
谢谢.
来福/
最简单的方法是NSTimer在主线程上运行循环.我建议您在应用程序委托上实现以下代码,并setupTimer从中调用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
}
Run Code Online (Sandbox Code Playgroud)
如果你的东西需要很长时间,并且你无法阻止主线程,那么使用以下方法调用你的东西:
[self performSelectorInBackground:@selector(myStuff) withObject:nil];
Run Code Online (Sandbox Code Playgroud)
或者您可以NSTimer使用类似的东西在后台线程上运行(我故意泄漏线程对象):
-(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
}
Run Code Online (Sandbox Code Playgroud)
你可以有一个计时器,查看NSTimer,每隔10分钟就会启动一次,为了让它在后台发生,你有一些选项可能是名字二.首先要注意的是,任何UI工作都不应该在另一个线程中完成,因为UIKit不是线程安全的.
您可以继承NSThread并使用它来在后台进行处理
您可以使用NSObjects performSelectorInBackground方法,它基本上创建一个线程并执行该方法.下面是参考http://developer.apple.com/iphone/library/documentation/Cocoa/Reference/Foundation/Classes/NSObject_Class/Reference/Reference.html#//apple_ref/occ/instm/NSObject/performSelectorInBackground:withObject:
| 归档时间: |
|
| 查看次数: |
12199 次 |
| 最近记录: |