码迷,mamicode.com
首页 > 编程语言 > 详细

多线程

时间:2015-08-20 15:23:30      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:

使用系统提供的创建子线程的方法,自动开启.对于耗时的工作,我们需要将工作交给子线程去做.主线程来执行界面的加载和处理用户的交互.这样我们就可以提高用户的体验度

<span style="font-size:24px;">   NSLog(@"thread = %@  isMainThread =  %d",[NSThread currentThread],[NSThread isMainThread]);</span>

 [NSThread detachNewThreadSelector:@selector(task1) toTarget:self withObject:nil];//   withObject代表的是@selector(task1)中task1方法所带的参数

    //2手动创建子线程
//    NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(task1) object:nil];
//    [thread start];
//    [thread release];

手动创建的线程一定要记得开启.


3  使用NSobject

<span style="font-size:24px;">    [self performSelectorInBackground:@selector(downLoadImage) withObject:nil];
   [self performSelectorInBackground:@selector(timerAction) withObject:nil];</span>
- (void)downLoadImage
{

    @autoreleasepool {
        NSString *urlSTr = @"http://image.zcool.com.cn/56/13/1308200901454.jpg";
        NSURL *url = [NSURL URLWithString:urlSTr];
        
        //从网络请求资源都是二进制数据
        
    //内存泄露,原因:在子线程执行的方法中系统默认不会加自动释放池
        NSData *imageData = [NSData dataWithContentsOfURL:url];
        [self performSelectorOnMainThread:@selector(loadImage:) withObject:imageData waitUntilDone:YES];
      
    }
  }

- (void)timerAction
{
    //子线程中存在事件循环处理机制(Runloop,但是默认状态是关闭的,因此需要手动开启)
    [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(otuPutAction) userInfo:nil repeats:YES];
    //打开runloop:(子线程默认是有runLoop的,但是默认是关闭的)
    [[NSRunLoop currentRunLoop] run];
}


<span style="font-size:18px;"> //4 线程队列:    NSOperationQueue
    //1??  创建任务
    NSInvocationOperation *operation1 = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(task2:) object:@"cuijin"];
    NSInvocationOperation *operation2 = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(task3:) object:@"liyang"];
    
    //2??  创建队列
    NSOperationQueue *queue = [[NSOperationQueue alloc]init];
    
    //3??  添加任务
    [queue addOperation:operation1];
    [queue addOperation:operation2];
    
    //4??  释放所有权
    [queue release];
    [operation2 release];
    [operation1 release];</span>



版权声明:本文为博主原创文章,未经博主允许不得转载。

多线程

标签:

原文地址:http://blog.csdn.net/cola_wh/article/details/47807045

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!