1. 程式人生 > >IOS在子執行緒中使用定時器,將定時器新增至RunLoop中

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:

1.0f target:self selector:@selector(timerAction) userInfo:nil repeats:YES];        

//將定時器新增到runloop

[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];        

[[NSRunLoop currentRunLoop] run];        

NSLog(@"多執行緒結束");    

}  

}

- (void)timerAction{  

//定時器也是在子執行緒中執行的

if

(![NSThread isMainThread])

 {       

NSLog(@"定時器");    

  }

}