IOS疯狂基础之多线程编程NSThread

关于等待

            returnData=[[myhttp.resultsDictionary valueForKey:@"body"] valueForKey:@"list"];

            while (!returnData) {

                returnData = [[myhttp.resultsDictionary valueForKey:@"body"] valueForKey:@"list"];

                [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];

            }



 iOS有三种多线程编程的技术,分别是:

1.、NSThread 

2、Cocoa NSOperation (iOS多线程编程之NSOperation和NSOperationQueue的使用

3、GCD  全称:Grand Central Dispatch( iOS多线程编程之Grand Central Dispatch(GCD)介绍和使用

这三种编程方式从上到下,抽象度层次是从低到高的,抽象度越高的使用越简单,也是Apple最推荐使用的。


NSThread:

优点:NSThread 比其他两个轻量级

缺点:需要自己管理线程的生命周期,线程同步。线程同步对数据的加锁会有一定的系统开销


NSThread 有两种直接创建方式

//1. 直接创建线程并且开始运行线程
[NSThread detachNewThreadSelector:@selector(doSomething:) toTarget:self withObject:nil];

//2.先创建线程对象,然后再运行线程

NSThread* myThread = [[NSThread alloc] initWithTarget:self selector:@selector(doSomething:)  object:nil];  

[myThread start];  



  1. -(void)downloadImage:(NSString *) url{  
  2.     NSData *data = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:url]];  
  3.     UIImage *image = [[UIImage alloc]initWithData:data];  
  4.     if(image == nil){  
  5.           
  6.     }else{  
  7. //通知主线程
  8.         [self performSelectorOnMainThread:@selector(updateUI:) withObject:image waitUntilDone:YES];  
  9.     }  

关于 waitUntilDone

- (void)changePopoverSize

{

    [self performSelectorOnMainThread:@selector(changeText:) withObject:@"Happy aha111" waitUntilDone:YES];

    NSLog(@"changePopoverSize#####end");

    sleep(5);

    NSLog(@"changePopoverSize-----end");

}

执行结果如下:


2012-08-17 17:19:29.618 awrbv[2024:f803] changeText:(NSString *)string

2012-08-17 17:19:29.619 awrbv[2024:f803] changePopoverSize#####end

2012-08-17 17:19:34.620 awrbv[2024:f803] changePopoverSize-----end

可以看出,如果waitUntilDone:YES那么等changeText执行完毕后再往下执行

如果waitUntilDone:NO的话,结果如下:


2012-08-17 17:21:12.135 awrbv[2049:f803] changePopoverSize#####end

2012-08-17 17:21:17.137 awrbv[2049:f803] changePopoverSize-----end

2012-08-17 17:21:17.139 awrbv[2049:f803] changeText:(NSString *)string



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值