首页 > 移动平台 > 详细

ios-网络

时间:2014-04-13 18:57:27      阅读:606      评论:0      收藏:0      [点我收藏+]
bubuko.com,布布扣
//多线程的几种方式,多线程是在调用结束之后就销毁了,主线程一直都在运行之中,所以不会销毁主线程,只有后台挂起
1.需要自己启动的方式
   NSString *str=@"liyang";
    NSThread *thread= [[NSThread alloc]initWithTarget:self selector:@selector(testThread:) object:str];
    [thread start];

-(void)testThread:(NSString *)ss{

    NSLog(@"%@",ss);
}
//这种,我们可以在需要的时候再启动。
bubuko.com,布布扣
2.使用类方法启动多线程
 [NSThread detachNewThreadSelector:@selector(testThread:) toTarget:self withObject:@"nimei"];
bubuko.com,布布扣
3.第三种方式
[self performSelectorInBackground:@selector(testThread:) withObject:@"水货"];//这个比较好用
bubuko.com,布布扣
4.第四种方式
 NSOperationQueue*operationqueue= [[NSOperationQueue alloc]init];//NSOperationQueue这个就类似一个线程池
    [operationqueue addOperationWithBlock:^{
        [NSThread sleepForTimeInterval:5];
        NSLog(@"%@",@"ddd");
    }];
bubuko.com,布布扣
5.第5种方式 
   NSOperationQueue*operationqueue= [[NSOperationQueue alloc]init];
    NSInvocationOperation *op=[[NSInvocationOperation alloc]initWithTarget:self selector:@selector
(testThread:) object:@"gggg"]; [operationqueue addOperation:op];
bubuko.com,布布扣
bubuko.com,布布扣
bubuko.com,布布扣
bubuko.com,布布扣
bubuko.com,布布扣

 

bubuko.com,布布扣
//线程总结:
//通过线程池来启动的时候我们可以设置最大并发数量 
operationqueue.maxConcurrentOperationCount=1;
bubuko.com,布布扣
[self performSelectorOnMainThread:@selector(testThread:) withObject:@"shuiB" waitUntilDone:YES];//多线程的时候要跳回主线程的方法,其中最后一个参数是指定是否等本方法执行完成之后再跳转,还是不用等直接跳转
bubuko.com,布布扣
bubuko.com,布布扣

 

bubuko.com,布布扣
 dispatch_queue_t queue=dispatch_queue_create("test", NULL);//创建一个队列
    dispatch_async(queue, ^{   //异步执行就是多线程
        [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类似
bubuko.com,布布扣

 

bubuko.com,布布扣
#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
//这段代码是一个扩展类,异步从网络上取得图片
bubuko.com,布布扣

 

ios-网络,布布扣,bubuko.com

ios-网络

原文:http://www.cnblogs.com/liyang31tg/p/3662397.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!