我正试图在iPhone的后台运行一个长时间的任务.我开始吧performSelectorInBackground.我还在NSTimer主线程上创建一个只是为了检查是否有效.我期望计时器会在另一个线程运行时运行:
- (void)viewDidLoad
{
[super viewDidLoad];
[NSTimer scheduledTimerWithTimeInterval:0.1 target:self
selector:@selector(onTimerEvent:)
userInfo:nil repeats:YES];
[self performSelectorInBackground:@selector(lengthyMethod) withObject:nil];
NSLog(@"Here we go!");
}
- (void)onTimerEvent:(NSTimer *)timer
{
NSLog(@"timer!");
}
Run Code Online (Sandbox Code Playgroud)
该lenghtyMethod执行的东西很多,包括使用URL下载ASIHTTPRequest等.
输出NSLog如下所示:
2011-03-11 15:17:07.470 MyApp[6613:207] Here we go!
2011-03-11 15:17:07.570 MyApp[6613:207] timer!
2011-03-11 15:17:07.670 MyApp[6613:207] timer!
// ... several seconds of output from lenghtyMethod omitted ...
2011-03-11 15:17:11.075 MyApp[6613:207] timer!
2011-03-11 15:17:11.170 MyApp[6613:207] timer!
// ... etc ... timer runs as expected when the call …Run Code Online (Sandbox Code Playgroud)