ios-网络
//多线程的几种方式,多线程是在调用结束之后就销毁了,主线程一直都在运行之中,所以不会销毁主线程,只有后台挂起 1.需要自己启动的方式 NSString *str=@"liyang"; NSThread *thread= [[NSThread alloc]initWithTarget:self selector:@selector(testThread:) object:str]; [thread start]; -(void)testThread:(NSString *)ss{ NSLog(@"%@",ss); } //这种,我们可以在需要的时候再启动。
2.使用类方法启动多线程 [NSThread detachNewThreadSelector:@selector(testThread:) toTarget:self withObject:@"nimei"];
3.第三种方式 [self performSelectorInBackground:@selector(testThread:) withObject:@"水货"];//这个比较好用
4.第四种方式 NSOperationQueue*operationqueue= [[NSOperationQueue alloc]init];//NSOperationQueue这个就类似一个线程池 [operationqueue addOperationWithBlock:^{ [NSThread sleepForTimeInterval:5]; NSLog(@"%@",@"ddd"); }];
5.第5种方式 NSOperationQueue*operationqueue= [[NSOperationQueue alloc]init]; NSInvocationOperation *op=[[NSInvocationOperation alloc]initWithTarget:self selector:@selector
(testThread:) object:@"gggg"]; [operationqueue addOperation:op];
//线程总结: //通过线程池来启动的时候我们可以设置最大并发数量 operationqueue.maxConcurrentOperationCount=1;
[self performSelectorOnMainThread:@selector(testThread:) withObject:@"shuiB" waitUntilDone:YES];//多线程的时候要跳回主线程的方法,其中最后一个参数是指定是,这个多线程是否等待主线程调用这个方法,再往下执行,yes表示等待,那么多线程就会卡死在这里,如果no就不会等待,估计就会将这个方法丢到主线程的队列中,等待执行,而多线程就会继续执行,不被卡死在这里
dispatch_queue_t queue=dispatch_queue_create("test", NULL);//创建一个队列 dispatch_async(queue, ^{ //异步执行就是多线程
@autoreleasepool{ //多线程要添加自动释放池,否则就没有自动释放池(2015年)
[NSThread sleepForTimeInterval:5]; NSLog(@"%@",@"liyang"); if([NSThread isMainThread]){ NSLog(@"isMainThread"); }else{ NSLog(@"isnotMainThread"); } dispatch_sync(dispatch_get_main_queue(), ^{//同步执行,跳回主线程 if([NSThread isMainThread]){ NSLog(@"isMainffffThread"); }else{ NSLog(@"nnnn");} });
} }); 对上面这段代码的简单理解:异步就是多线程,同步就是主线程,这个应该和java的ajax类似
dispatch_async:会单独开启一个线程来执行这个队列,而这个队列里就是这个block,
dispatch_sync:不会单独开始线程,只是简单的将block添加到一个指定的队列里(大概意思是这样,测试还是有点问题,待解决)
#import "UIImageView+WebCath.h" @implementation UIImageView (WebCath) -(void) setImageWithURL:(NSURL *)url{ dispatch_queue_t quence= dispatch_queue_create("loadimage", NULL); dispatch_async(quence, ^{ NSData *data=[NSData dataWithContentsOfURL:url]; UIImage *image=[UIImage imageWithData:data]; dispatch_sync(dispatch_get_main_queue(), ^{ self.image=image; }); }); } @end //这段代码是一个扩展类,异步从网络上取得图片
1.这里只记录一些学习笔记
2.这里只记录一些学习心得,如果心得方向有错,请留言
2.这里只记录一些日记(只为提升英语,暂时有点忙,等转行了开始写)

浙公网安备 33010602011771号