standford open course iOS7 develop Lecture10

来源:互联网 发布:使用管家婆存入软件 编辑:程序博客网 时间:2024/04/30 23:07

multithreading

技术功能:把程序要执行的任务分成多个部分,同时在处理器中执行。原因,某些任务可能会造成阻塞,如等待返回网络数据时。

in iOS 由queue 来实现,不同queue中的代码块,block,排队等待被执行。serial queue 串行队列,还有concurrent queue并行队列。

Main queue 监听用户,同步UI,不希望被阻塞。会在安静一会儿之后再执行其他的block

Demo: download the contents of an url

 

UIScrollview: 里面的内容可以滚动,放大,缩小。以放下更多的内容。

Create: Drag it. But put the subviews by code。

 

Demo在其他队列下载图片,完成后通知主队列,并显示在imageView里面。在执行下载过程中,需要时间,执行完成后,要检查一下是否依然满足开始执行它的要求。

1. 在一个在运行时会被调用的方法中,依次创建一个NSURLRequest *request, NSURLSessionConfiguration *configuration, NSURLSession *session,  NSURLSessionDownloadTask *task, 然后执行[task resume]

-(void)startDownloadingImage{    self.image = nil;    if (self.imageURL) {        NSURLRequest *request = [[NSURLRequest alloc] initWithURL:self.imageURL];        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration ephemeralSessionConfiguration];        NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];        NSURLSessionDownloadTask *task = [session downloadTaskWithRequest:request completionHandler:^(NSURL *localfile, NSURLResponse *response, NSError *error) {            if (!error) {                if ([self.imageURL isEqual:request.URL]) {                    UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:localfile]];                    [self performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:NO];//                    dispatch_async(dispatch_get_main_queue(), ^{ self.image = image; }); //Totally C的方法also can work                }            }        }];        [task resume];    }}


0 0