您的位置:首页 > 移动开发 > Objective-C

Objective-c中线程NSThread的使用

2013-09-27 16:36 363 查看
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);
};
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: