IOS 线程处理

来源:未知 责任编辑:责任编辑 发表时间:2013-12-22 14:54 点击:

IOS中,如果要在主线程中启动一个子线程,可以又两种方法:

[cpp] 
[NSThread detachNewThreadSelector:@selector(myThreadMainMethod:) toTarget:self withObject:nil]; 
这是在cocoa早期提供的方法,因此你可以在任何版本的ios和mac上调用此方法。
在 OS X v10.5(or later)和IOS中,苹果又提供了一种方法,可以允许你获得你的thread句柄,并且更方便的让主线程控制子线程。

[cpp] 
NSThread* myThread = [[NSThread alloc] initWithTarget:self 
                                        selector:@selector(myThreadMainMethod:) 
                                        object:nil]; 
[myThread start];  // Actually create the thread 

如果要停止子线程,有两种方法:
第一种,是在子线程中执行:

[cpp] 
[NSThread exit]; 

另一种是在主线程执行:
[cpp]
[myThread cancel];  
要注意的是,[mThread cancel]; 并不能exit线程,只是标记为canceled,但线程并没有死掉。加入你在子线程中执行了一个循环,则cancel后,循环还在继续,你需要在循环的条件判断中加入 !mThread.isCancelled 来判断子线程是否已经被cancel来决定是否继续循环。

下面是我的一个测试demo,可以参考一下:
[cpp] 
@synthesize mThread; 
- (void)viewDidLoad 

    [super viewDidLoad]; 
     
    NSLog(@"main thread:%@",[NSThread currentThread]); 
     mThread=[[NSThread alloc] initWithTarget:self selector:@selector(subThreadMethod) object:nil]; 
    [NSThread detachNewThreadSelector:@selector(performMethod) toTarget:self withObject:nil]; 
  

-(void)subThreadMethod{ 
    int i=1; 
    while (i++>0 && ![[NSThread currentThread]isCancelled]) { 
        NSLog(@"subthread i:%d ,thread:%@",i,[NSThread currentThread]); 
    }   

 
- (IBAction)startThread:(id)sender { 
    NSLog(@"startThread...."); 
    [mThread start]; 

 
- (IBAction)stopThread:(id)sender { 
    NSLog(@"mThread.isCancelled: %d",mThread.isCancelled); 
    if (!mThread.isCancelled) { 
        [mThread cancel]; 
//        [mThread exit]; //exit 是类方法,不可以用在对象上 

发表评论
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
用户名: 验证码:点击我更换图片
最新评论 更多>>

推荐热点

  • Lexical or Preprocessor Issue 'xxx.h
  • ios学习笔记(二)xcode 4.3.2下实现基本交互
  • ios版本的helloworld
  • iphone(object-c) 内存管理(3) 有效的内存管理 前半部分
  • ios学习笔记(一)xcode 4.3.2下创建第一个ios项目
  • IOS类似iphone通讯录TableView的完整demo【附源码】
  • UITableView一些方法
  • [iPhone中级]iPhone团购信息客户端的开发 (二)
  • 如何为Iphone应用创建启动界面
网站首页 - 友情链接 - 网站地图 - TAG标签 - RSS订阅 - 内容搜索
Copyright © 2008-2015 计算机技术学习交流网. 版权所有

豫ICP备11007008号-1