iOS开发学习之路【高级主题】——多线程、网络编程
目录
NSThread
初始化一个 NSThread 的三种方法
-
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); } }
-
继承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..."); }
-
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
创建
-
使用 NSOperation 创建
#import "MyOperation.h" - (IBAction)start:(UIButton *)sender { MyOperation *o = [[MyOperation alloc]init]; NSOperationQueue *q = [[NSOperationQueue alloc]init]; [q addOperation:o]; }
-
使用 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); } }
-
使用 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);
}];