IOS在子執行緒中使用定時器,將定時器新增至RunLoop中
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
//用NSObject的方法建立一個多執行緒
[self performSelectorInBackground:@selector(multiThread) withObject:nil];
returnYES;
}
-(void)multiThread{
if (![NSThread isMainThread]) {
// 第1種方式
//此種方式建立的timer已經新增至runloop中
//[NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
//保持執行緒為活動狀態,才能保證定時器執行
// [[NSRunLoop currentRunLoop] run];//已經將nstimer新增到NSRunloop中了
//第2種方式
//此種方式建立的timer沒有新增至runloop中
NSTimer *timer = [NSTimer timerWithTimeInterval:
//將定時器新增到runloop中
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
[[NSRunLoop currentRunLoop] run];
NSLog(@"多執行緒結束");
}
}
- (void)timerAction{
//定時器也是在子執行緒中執行的
if
{
NSLog(@"定時器");
}
}