IOS開發中多線程的使用,ios開發多線程

來源:互聯網
上載者:User

IOS開發中多線程的使用,ios開發多線程

一、建立多線程的五種方式
1.開啟線程的方法一
    NSThread * thread=[[NSThread alloc] initWithTarget:self selector:@selector(_update) object:nil];
2.開啟線程的方法二 
    [NSThread detachNewThreadSelector:@selector(_update) toTarget:self withObject:nil];
3.開啟線程的方法三
    [self performSelectorInBackground:@selector(_update) withObject:nil];
4.開啟線程的方法四
    NSOperationQueue *queue=[[NSOperationQueue alloc] init];    [queue addOperationWithBlock:^{        for(int i=0;i<50;i++){            printf("子線程\n");        }    }];
5.開啟線程的方法五
    //第一步開啟線程池        NSOperationQueue * queue=[[NSOperationQueue alloc] init];    //設定並發數目    [queue setMaxConcurrentOperationCount:2];        //第二部建立多線程添加到線程池    NSInvocationOperation * thread1=[[NSInvocationOperation alloc] initWithTarget:self selector:@selector(_update1) object:nil];    NSInvocationOperation *thread2=[[NSInvocationOperation alloc] initWithTarget:self selector:@selector(_update2) object:nil];        [thread1 setQueuePriority:NSOperationQueuePriorityVeryLow];    [thread2 setQueuePriority:NSOperationQueuePriorityVeryHigh];        [queue addOperation:thread1];    [queue addOperation:thread2];
二、多線程應用執行個體,載入圖片。
1.核心思想

  考慮到如果載入網狀圖片會延遲,在一個主線程載入會影響控制項的渲染,此時可以採取多線程,非同步載入完成後重新整理UI。

2.實現思路

  通過為UIImageView 增加類目來實現多線程下載。

  主要代碼:

#import "UIImageView+thread.h"@implementation UIImageView(load)- (void) setImageWithUrl:(NSString *)url{    [self performSelectorInBackground:@selector(_loadImage:) withObject:url];}- (void) _loadImage:(NSString *)u{    @autoreleasepool {                NSURL *url=[NSURL URLWithString:u];        NSData *data=[NSData dataWithContentsOfURL:url];        UIImage *image=[UIImage imageWithData:data];                [self performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:NO];            }}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.