美文网首页
iOS 异步操作

iOS 异步操作

作者: 风之化身呀 | 来源:发表于2018-11-09 00:28 被阅读171次

1.NSThread

  • 启动子线程
    1、[thread start]
    2、detachNewThreadSelector
    3、performSelectorInBackground(推荐)
     //方法1:使用对象方法
    //创建一个线程,第一个参数是请求的操作,第二个参数是操作方法的参数
    NSThread *thread=[[NSThread alloc]initWithTarget:self selector:@selector(loadImage) object:nil];
    //启动一个线程,注意启动一个线程并非就一定立即执行,而是处于就绪状态,当系统调度时才真正执行
    [thread start];
    
    //方法2:使用类方法
    [NSThread detachNewThreadSelector:@selector(loadImage) toTarget:self withObject:nil];

    // 方法3:使用 performSelectorInBackground
    [self performSelectorInBackground:@selector(loadImage:) withObject:[NSNumber numberWithInt:i]];
  • 回到主线程
    performSelectorOnMainThread,是NSObject的分类方法,每个NSObject对象都有此方法
[self performSelectorOnMainThread:@selector(updateImage:) withObject:data waitUntilDone:YES];

2.NSBlockOperation

  • 启动子线程
//创建操作队列
NSOperationQueue *operationQueue=[[NSOperationQueue alloc]init];
operationQueue.maxConcurrentOperationCount=5;//设置最大并发线程数
[operationQueue addOperationWithBlock:^{
    [self loadImage:[NSNumber numberWithInt:i]];
 }];
  • 回到主线程
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
     [self updateImageWithData:data andIndex:i];
}];

3.GCD

  • 启动子线程
/*创建一个串行队列
     第一个参数:队列名称
     第二个参数:队列类型
 */
    dispatch_queue_t serialQueue=dispatch_queue_create("myThreadQueue1", DISPATCH_QUEUE_SERIAL);//注意queue对象不是指针类型
    dispatch_async(serialQueue, ^{
         [self loadImage:[NSNumber numberWithInt:i]];
    });
  • 回到主线程
    // 获取主线程
    dispatch_queue_t mainQueue= dispatch_get_main_queue();
    dispatch_sync(mainQueue, ^{
        [self updateImageWithData:data andIndex:i];
    });

锁机制 @synchronized

解决资源抢占的问题

-(NSData *)requestData:(int )index{
    NSData *data;
    NSString *name;
    //线程同步
    @synchronized(self){
        if (_imageNames.count>0) {
            name=[_imageNames lastObject];
            [_imageNames removeObject:name];
        }
    }
    if(name){
        NSURL *url=[NSURL URLWithString:name];
        data=[NSData dataWithContentsOfURL:url];
    }
    return data;
}

相关文章

  • iOS-14 线程基础

    参考 ios的线程和同步异步操作 - 简书线程 同步异步 Timer 等使用 本文主要从 1、 ios三种创建方式...

  • iOS 异步操作

    1.NSThread 启动子线程1、[thread start]2、detachNewThreadSelector...

  • Swift 中的异步与并发

    异步 异步在 iOS 里是一个常见的操作,例如要在网络请求后更新数据模型和视图。但是当异步操作嵌套时,不仅容易出现...

  • iOS多线程之NSOpearation

    在 iOS 开发中,异步操作通常使用 GCD 的方式来完成,GCD 可以简单快速完成异步操作,当如果涉及到高级的操...

  • 无奈,无赖,谁来拯救你!

    1.在ios中很多操作在异步操作的时候需要等待,异步操作完成时候,我们有时候会这样处理: 当然采取同步的就不说了....

  • [iOS][OC] 自定义 Promise 处理串行的异步操作

    背景 iOS 应用中很多操作是异步的,比如: 网络请求的回调 UIAlertController 等待用户点击事件...

  • ES6 Primise异步编程

    异步操作流程化的手段 #Promise处理异步操作 Promise,使异步操作变得流程化的手段之一,例如“异步A ...

  • ios 异步执行耗时操作

  • Promise--异步的解决方案

    Promise 对象是 JavaScript 的异步操作解决方案,为异步操作提供统一接口,使得异步操作具备同步操作...

  • .NET多线程(五)异步操作

    5、异步操作 5.1 异步操作基础 异步操作发展历史,APM模式,EAP模式,TPL模式 .NET 1.0 Sys...

网友评论

      本文标题:iOS 异步操作

      本文链接:https://www.haomeiwen.com/subject/heugxqtx.html