關於等待
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 有兩種直接創建方式
//2.先創建線程對象,然後再運行線程
NSThread* myThread = [[NSThread alloc] initWithTarget:self selector:@selector(doSomething:)
object:nil];
[myThread start];
- -(void)downloadImage:(NSString *) url{
- NSData *data = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:url]];
- UIImage *image = [[UIImage alloc]initWithData:data];
- if(image == nil){
- }else{
-
//通知主線程
- [self performSelectorOnMainThread:@selector(updateUI:) withObject:image waitUntilDone:YES];
- }
- }
關於 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