#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产生的是可变对象。
本文探讨了在 iOS 应用中使用不同方式下载并显示图片的方法,包括同步与异步下载的区别及其对主线程的影响。同时介绍了如何正确地在主线程更新 UI,确保应用的流畅运行。
902

被折叠的 条评论
为什么被折叠?



