iOS开发笔记_5.线程,HTTP请求,定时器
说起线程,不会陌生了,操作系统课程里已经详细介绍了这个东东,这里就不解释了,想要了解的问问百度或者翻翻书。
线程的创建
总结了昨天的学习,有下面几种创建的方式。
//第一种
NSThread *t = [[NSThread alloc] initWithTarget:self selector:
@selector(mutitly) object:nil];
[t start];
//第二种
[NSThread detachNewThreadSelector:@selector(mutitly) toTarget:self withObject:nil];
//第三种,这种比较常用
[self performSelectorInBackground:@selector(mutitly) withObject:nil];
//第四种
NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init];
[operationQueue addOperationWithBlock:^{ for (int i = ; i < ; i++) {
NSLog(@"多线程 :%d",i);
}
}];
//第五种创建线程队列(线程池 )
NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init];
//设置线程池中得并发数
operationQueue.maxConcurrentOperationCount = ; NSInvocationOperation *invocation1 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(thread1) object:nil];
[invocation1 setQueuePriority:NSOperationQueuePriorityVeryLow]; NSInvocationOperation *invocation2 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(thread2) object:nil];
[invocation2 setQueuePriority:NSOperationQueuePriorityVeryHigh]; [operationQueue addOperation:invocation1];
[operationQueue addOperation:invocation2];
这个例子是在做实验的时候总结的
-(void)setImageWithURL:(NSURL *) url{
//加载网络图片的时候应该开启一个线程,不然加载的时候会阻塞
[self performSelectorInBackground:@selector(loadData:) withObject:url];
//不推荐使用这种方法调用,因为这时候按钮会卡住
//[self loadData:url];
}
-(void)loadData:(NSURL *) url{
@autoreleasepool {
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
//在主线程上执行setImage方法
[self performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:YES];
}
}
应该注意的是,加载网络数据的时候,最好要开启一个新的线程,并且,要把网络上得图片加载到本地的话,应该在主线程上调用,这里调用的是performSelectorOnMainThread:方法,这个很重要,有关UI的操作都是在主线程上进行的。
HTTP请求
用户发送请求的时候有多种请求方式,比较常见的请求方式有两种
1、“get”请求:向服务器索取数据
2、“post”请求,向服务器提交数据,如“用户登录”等等。
同步请求(只能等服务器的数据完全返回响应后,程序才往下执行)
NSURL *url = [NSURL URLWithString:@"http://www.baidu.com"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//设置请求方式
[request setHTTPMethod:@"GET"];
//设置请求时间
[request setTimeoutInterval:];
NSURLResponse *respon ;
NSError *error = nil;
//发送一个同步请求
NSData *data = [NSURLConnection sendSynchronousRequest:request
returningResponse:&respon error:&error];
NSInteger statusCode = [respon statusCode];
NSLog(@"响应码:%d",statusCode);
NSDictionary *headFields = [respon allHeaderFields];
NSLog(@"响应头:%@",headFields);
NSString *htmlstring = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@",htmlstring);
异步请求(不用等服务器完全响应,程序边执行边加载数据)
- (IBAction)asynchAction:(id)sender {
NSURL *url = [NSURL URLWithString:@"http://www.baidu.com"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//设置请求方式
[request setHTTPMethod:@"GET"];
//设置请求时间
[request setTimeoutInterval:];
//发送异步请求
[NSURLConnection connectionWithRequest:request delegate:self];
//第二种异步请求方式,用的不是很多
// NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init];
//
// [NSURLConnection sendAsynchronousRequest:request queue:operationQueue completionHandler:^(NSURLResponse *respon, NSData *data, NSError *error) {
// if([NSThread isMultiThreaded]){
// NSLog(@"是多线程");
// }
//
// NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
// NSLog(@"%@",string);
//
// }];
主要是要知道url,request的创建,还有请求的方式是同步还是异步。
总结一下访问网络的基本流程。
1、构造NSURL实例(地址)
2、生成NSURLRequest(请求)
3、通过NSURLConnection发送请求
4、通过NSURLRespond实例和NSError实例分析结果
5、接收返回的数据
还有几个比较常用的协议方法,NSURLConnectionDataDelegate
//服务器响应的方法
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{ NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
NSDictionary *allHeadFields = [httpResponse allHeaderFields];
NSLog(@"%@",allHeadFields);
}
//接受数据的方法,会调用多次,每一次调用服务器的一部分数据data
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{ [resultData appendData:data]; }
//数据加载完成调用的方法
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{ NSString *htmlString = [[NSString alloc] initWithData:resultData encoding:NSUTF8StringEncoding];
NSLog(@"%@",htmlString); }
定时器
-(void)mutiThread{
//多线程里面开启一个定时器可以提高精确度
//启动定时器
NSLog(@"定时器启动");
@autoreleasepool {
[NSTimer scheduledTimerWithTimeInterval: target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];
}
//获取当前的runloop,线程就停在这里
[[NSRunLoop currentRunLoop] run];
NSLog(@"after");
}
-(void)timerAction:(NSTimer *) timer
{
index++;
NSLog(@"定时器打印");
if (index == ) {
[timer invalidate];
}
}
实现的功能是每隔1秒钟就执行一次timerAction方法,一共执行五次,五次后打印后就结束
iOS开发笔记_5.线程,HTTP请求,定时器的更多相关文章
- IOS开发笔记(4)数据离线缓存与读取
IOS开发笔记(4)数据离线缓存与读取 分类: IOS学习2012-12-06 16:30 7082人阅读 评论(0) 收藏 举报 iosiOSIOS 方法一:一般将服务器第一次返回的数据保存在沙盒里 ...
- 【iOS系列】-iOS开发,GET,POST请求使用
[iOS系列]-iOS开发,GET,POST请求使用 步骤: 1:实例化URL(网络资源) 2:根据URL建立URLRequest(网络请求) 默认为GET请求: 对于POST请求,需要创建请求的数据 ...
- iOS开发多线程篇—线程安全
iOS开发多线程篇—线程安全 一.多线程的安全隐患 资源共享 1块资源可能会被多个线程共享,也就是多个线程可能会访问同一块资源 比如多个线程访问同一个对象.同一个变量.同一个文件 当多个线程访问同一块 ...
- iOS开发多线程篇—线程间的通信
iOS开发多线程篇—线程间的通信 一.简单说明 线程间通信:在1个进程中,线程往往不是孤立存在的,多个线程之间需要经常进行通信 线程间通信的体现 1个线程传递数据给另1个线程 在1个线程中执行完特定任 ...
- iOS开发多线程篇—线程的状态
iOS开发多线程篇—线程的状态 一.简单介绍 线程的创建: self.thread=[[NSThread alloc]initWithTarget:self selector:@selector(te ...
- iOS开发笔记7:Text、UI交互细节、两个动画效果等
Text主要总结UILabel.UITextField.UITextView.UIMenuController以及UIWebView/WKWebView相关的一些问题. UI细节主要总结界面交互开发中 ...
- iOS开发笔记-两种单例模式的写法
iOS开发笔记-两种单例模式的写法 单例模式是开发中最常用的写法之一,iOS的单例模式有两种官方写法,如下: 不使用GCD #import "ServiceManager.h" ...
- iOS开发笔记--什么时候调用layoutSubviews
iOS开发笔记--什么时候调用layoutSubviews 分类: iOS2014-04-22 16:15 610人阅读 评论(0) 收藏 举报 今天在写程序时候遇见layoutSubviews触发时 ...
- IOS开发笔记 IOS如何访问通讯录
IOS开发笔记 IOS如何访问通讯录 其实我是反对这类的需求,你说你读我的隐私,我肯定不愿意的. 幸好ios6.0 以后给了个权限控制.当打开app的时候你可以选择拒绝. 实现方法: [plain] ...
随机推荐
- BZOJ 2063: 我爸是李刚
2063: 我爸是李刚 Time Limit: 10 Sec Memory Limit: 64 MBSubmit: 155 Solved: 82[Submit][Status][Discuss] ...
- 【BZOJ】1592: [Usaco2008 Feb]Making the Grade 路面修整
[算法]动态规划DP [题解] 题目要求不严格递增或不严格递减. 首先修改后的数字一定是原来出现过的数字,这样就可以离散化. f[i][j]表示前i个,第i个修改为第j个数字的最小代价,a表示排序后数 ...
- Oracle 脚本记录
给表创建序列或触发器 create or replace procedure p_createseq(tablename in varchar2,key in varchar2) Authid Cur ...
- 转:Android 调试桥(adb)是多种用途的工具
转自:http://my.oschina.net/xuwa/blog/1574 Android 调试桥(adb)是多种用途的工具,该工具可以帮助你你管理设备或模拟器 的状态. 可以通过下列几种方法加入 ...
- POJ1236 (强连通分量缩点求入度为0和出度为0的分量个数)
Network of Schools Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 13804 Accepted: 55 ...
- locust===注意事项
1.安装包在:微盘 2.运行命令是:locust -f load_test.py --host=https://www.baidu.com 3.本地打开的是:http://localhost:8089 ...
- Restful接口设计
URL设计规范:/模块/资源/{标示}/集合1/... eg: /user/{uid}/friends ->好友列表 例子:秒杀系统API设计 1.请求参数绑定:@PathVariable(&q ...
- 【 Linux 】I/O工作模型及Web服务器原理
一.进程.线程 进程是具有一定独立功能的,在计算机中已经运行的程序的实体.在早期系统中(如linux 2.4以前),进程是基本运作单位,在支持线程的系统中(如windows,linux2.6) ...
- Net Core 控制台程序使用Nlog 输出到log文件
using CoreImportDataApp.Common; using Microsoft.Extensions.Configuration; using Microsoft.Extensions ...
- 作业执行器Job Executor
Job Executor 激活作业执行器 AsyncExecutor是一个组件,它管理线程池,来触发计时器和其他异步任务.其他实现也是可能的(例如使用消息队列,请参阅用户指南的高级部分). 默认情况下 ...