NSThread使用
1.创建并启动线程
thread = [[NSThread alloc]initWithTarget:self selector:@selector(startMonitor) object:nil]; [thread start];
2.停止线程
先向线程发送cancel消息,将线程标记为停止,然后在合适的地方判断线程是否标记为退出,如果是,则发送exit消息,真正退出线程
- (void)getInfo:(id)sender { if (!running) { NSLog(@"start monitor"); thread = [[NSThread alloc]initWithTarget:self selector:@selector(startMonitor) object:nil]; [thread start]; running = true; } else{ NSLog(@"stop monitor"); [thread cancel]; running = false; } } - (void) startMonitor { while (true) { if ([[NSThread currentThread] isCancelled]) { [NSThread exit]; } //do your things here sleep(1); }; }