iOS开发学习之路【高级主题】——多线程、网络编程

NSThread

初始化一个 NSThread 的三种方法

  1. init

    - (instancetype)initWithTarget:(id)target selector:(SEL)selector object:(id)argument;
    
    - (IBAction)start:(id)sender {
        
        NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(loop) object:nil];
        //启动一个线程
        [thread start];
        
        NSLog(@"end...");
    }
    -(void)loop{
        for (int i = 1; i <= 10 ; i++) {
            [NSThread sleepForTimeInterval:1];
            NSLog(@"i=%d", i);
        }
    }
    
  2. 继承NSThread类

    //创建一个继承NSThread的类
    
    #import "MyNSThread.h"
    
    @implementation MyNSThread
    //重写main方法
    -(void)main{
        for (int j = 1; j<=10; j++) {
            [NSThread sleepForTimeInterval:1];
            NSLog(@"j=%d",j);
        }
    }
    @end
    
    - (IBAction)start:(id)sender {
        //初始化
        MyNSThread *thread = [[MyNSThread alloc]init];
        [thread start];
        
        NSLog(@"end...");
    }
    
  3. detachNewThread

    + (void)detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(nullable id)argument;
    
    - (IBAction)start:(id)sender {
    
        [NSThread detachNewThreadSelector:@selector(loop) toTarget:self withObject:nil];
        
        NSLog(@"end...");
    }
    -(void)loop{
        for (int i = 1; i <= 10 ; i++) {
            [NSThread sleepForTimeInterval:1];
            NSLog(@"newi=%d", i);
        }
    }
    

Operation Object

创建

  1. 使用 NSOperation 创建

    #import "MyOperation.h"
    
    
    - (IBAction)start:(UIButton *)sender {
        
        MyOperation *o = [[MyOperation alloc]init];
        NSOperationQueue *q = [[NSOperationQueue alloc]init];
        [q addOperation:o];
        
    }
    
  2. 使用 NSOperation 创建

     	NSInvocationOperation *o = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(loop) object:nil];
        NSOperationQueue *q = [[NSOperationQueue alloc]init];
        [q addOperation:o];
    
    
    -(void)loop{
        for(int j = 1; j <=10; j++){
            [NSThread sleepForTimeInterval:1];
            NSLog(@"j=%d",j);
        }
    }
    
  3. 使用 NSBlockOperation 创建

    	NSBlockOperation *o = [NSBlockOperation blockOperationWithBlock:^{
            for(int z = 1; z <=10; z++){
                [NSThread sleepForTimeInterval:1];
                NSLog(@"z=%d",z);
            }
        }];
        NSOperationQueue *q = [[NSOperationQueue alloc]init];
        [q addOperation:o];
    

效果

在这里插入图片描述

设置线程之间的依赖关系

	[q addOperation:o];
    [o1 addDependency:o];
    [q addOperation:o1];

在这里插入图片描述

GCD

GCD 简介

​ Grand Central Dispatch 是苹果主推的多线程处理机制,该多线程处理机制在多核CPU状态下,性能很高。GCD 一般和 Black 一起使用,在 Block 回调中处理程序操作。GCD 声明了一系列以 dispatch 打头的方法来实现多线程的操作,例如,获得线程队列、启动线程、异步线程等。

实现异步任务

    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queue, ^{
        [self loop];
    });

-(void)loop{
    for (int i = 1; i <= 10; i++) {
        [NSThread sleepForTimeInterval:1];
        NSLog(@"i=%d",i);
    }
}

三种调度队列

 dispatch_queue_t q = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(q, ^{
        [self update];
    });

-(void)update{
    float p = 0.0;
    while (p<1) {
        p+=0.01;
        [NSThread sleepForTimeInterval:0.1];
        dispatch_async(dispatch_get_main_queue(), ^{
            self.myProgress.progress  = p;
        });
    }
}

NSURLConnection网络编程

请求服务器数据

    // 1.NSURLRequest
    NSURL *url = [NSURL URLWithString:@"http://www.baidu.com"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    // 2.NSOperationQueue
    NSOperationQueue *quere = [[NSOperationQueue alloc]init];
    // 异步请求
    [NSURLConnection sendAsynchronousRequest:request queue:quere completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        NSString *content = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"%@",content);
    }];
    // 1.NSURLRequest
    NSURL *url = [NSURL URLWithString:@"http://www.baidu.com"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    // 2.NSOperationQueue
    NSOperationQueue *quere = [[NSOperationQueue alloc]init];
	// 同步请求
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURLResponse *response;
        NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
        NSLog(@"%@",data);
    });

向服务器发送数据

    //http://api.map.baidu.com/telematics/v3/weather?location=嘉兴&output=json&ak=5slgyqGDENN7Sy7pw29IUvrZ
    NSURL *url = [NSURL URLWithString:@"http://api.map.baidu.com/telematics/v3/weather"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSString *param = @"";
    NSData *body = [param dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:body];
    
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        NSString *content = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"%@",content);
    }];
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
网络编程中,多线程编程是一种常用的技术,可以提高程序的并发性和性能。下面是一些关于多线程编程的常用方法和注意事项: 1. NSThread:NSThread是iOS中最底层的线程类,它可以通过类方法或实例方法来创建线程。使用NSThread可以设置线程的名称、优先级,以及控制线程的睡眠和退出等操作。 2. 线程调度:在多线程编程中,多个线程会并发运行,但线程的执行顺序是由CPU调度器决定的,程序员无法控制。多个线程会同时竞争CPU资源,谁先抢到资源谁就先执行,所以多线程的执行顺序是随机的。 3. 多线程的创建:在iOS开发中,常用的多线程编程方式有三种:NSThread、GCD和NSOperation。NSThread是最底层的线程类,可以直接操作线程的各种属性和方法。GCD(Grand Central Dispatch)提供了一种高效的并发编程模型,可以通过队列来管理任务的执行。NSOperation是基于GCD的更高层次的封装,提供了更多的控制和管理线程的功能。 4. 线程的创建顺序:在多线程编程中,并不能保证哪个线程会先运行,即无法确定新创建的线程或调用线程哪个会先执行。新创建的线程可以访问进程的地址空间,并继承调用线程的浮点环境和信号屏蔽字,但挂起信号集会被清除。 总结来说,多线程编程是一种提高程序并发性和性能的技术,在网络编程中尤为重要。通过使用NSThread、GCD或NSOperation等方法,可以实现多线程的创建和管理。然而,程序员无法控制线程的执行顺序,因为线程的调度是由CPU调度器决定的。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [IOS多线程基础(OC)](https://blog.csdn.net/yong_19930826/article/details/105857055)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *3* [UNIX环境高级编程笔记](https://blog.csdn.net/w_x_myself/article/details/128613534)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值