ios多線程queue的差異,ios多線程queue
#import "ViewController.h"#import "View2Controller.h"@interface ViewController (){ UIImageView *img;}@end@implementation ViewController- (void)viewDidLoad{ [super viewDidLoad]; self.view.backgroundColor = [UIColor redColor]; img = [[UIImageView alloc] initWithFrame:CGRectMake(0, 20, 200, 200)]; img.backgroundColor = [UIColor greenColor]; [self.view addSubview:img]; UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect]; btn.frame = CGRectMake(30, 300, 100, 50); [btn setTitle:@"下載" forState:UIControlStateNormal]; [btn addTarget:self action:@selector(start) forControlEvents:UIControlEventTouchUpInside]; btn.backgroundColor = [UIColor cyanColor]; [self.view addSubview:btn]; UIButton *btn2 = [UIButton buttonWithType:UIButtonTypeRoundedRect]; btn2.frame = CGRectMake(150, 300, 100, 50); [btn2 setTitle:@"前往" forState:UIControlStateNormal]; [btn2 addTarget:self action:@selector(jumpTo) forControlEvents:UIControlEventTouchUpInside]; btn2.backgroundColor = [UIColor cyanColor]; [self.view addSubview:btn2]; //[self testcopy]; }/*實驗結果:async + globel 圖片下載成功,顯示有延遲 在main中設定圖片才正常async + main 正常sync + globel 圖片下載成功,顯示有延遲, 在main中設定才正常sync + main 圖片無法下載,線程卡死*/-(void)start{ img.image = nil; NSLog(@"start"); dispatch_async(dispatch_get_main_queue(), ^{ [self downloadImg]; }); NSLog(@"end");}-(void)downloadImg{ NSString *urlStr = @"http://cdn2.raywenderlich.com/wp-content/uploads/2012/09/iOS_6_feast.png"; NSURL *url = [NSURL URLWithString:urlStr]; NSError *error = nil; NSData *imgData = [[NSData alloc] initWithContentsOfURL:url options:NSDataReadingUncached error:&error]; NSLog(@"img downloaded %d",imgData.length);// dispatch_sync(dispatch_get_main_queue(), ^{// img.image = [UIImage imageWithData:imgData];// }); img.image = [UIImage imageWithData:imgData];}-(void)testcopy{ NSArray *a = [NSArray array]; NSMutableArray *b = [NSMutableArray array]; NSMutableArray *c = [a mutableCopy]; NSMutableArray *d = [b copy];// [c addObject:@"1"];// [d addObject:@"2"];}
async + globel 圖片下載成功,顯示有延遲 在main中設定圖片才正常async + main 正常sync + globel 圖片下載成功,顯示有延遲, 在main中設定才正常sync + main 圖片無法下載,線程卡死
copy與mutablecopy
copy產生的是不可變的對象
mutablecopy產生的是可變對象。