试图了解调度

时间:2016-04-23 21:06:39

标签: ios objective-c grand-central-dispatch

我试图了解Objective-C的调度机制。但是没有成功。

我有这两种方法:

- (void)downloadImage
        {
            NSString * URLString= @"http://www.something.com";
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
                   ^{
                       NSURL *imageURL = [NSURL URLWithString:fullURL];
                       NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
                       theImportant.image = [UIImage imageWithData:imageData];

                       dispatch_sync(dispatch_get_main_queue(), ^{

                           stopAnimate=true;
                           [self MoveToPosition:myView.center];



                       });
                   });
}

-(void)MoveToPosition:(CGPoint)position{
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [UIView animateWithDuration:1.5
                              delay:0.0
                            options:UIViewAnimationOptionCurveEaseInOut |UIViewAnimationOptionBeginFromCurrentState
                         animations:^{
                             myView.center=position;
                         }
                         completion:^(BOOL finished){
                             if (stopAnimate){
                                 //do Nothing
                             } else if (someFlag){
                                 [self downloadImage];
                             } 
                         }
         ];
}

因此,第一种方法由第二种方法调用,而第二种方法又调用第一种方法。

这样做很好,除了不显示 theImportant.image 的事实。

当我移动

theImportant.image = [UIImage imageWithData:imageData];

中的

dispatch_sync

阻止 downloadImage ,动画开始以意想不到的方式运行。

我确实意识到我并不完全理解调度,但我希望你的见解会增长我的智慧。

theImportant定义为

@property(强,原子)IBOutlet UIImageView * theImportant;

我的问题很简单:为什么我的theImportant.image没有显示。

2 个答案:

答案 0 :(得分:0)

我最后添加了

@property (strong, atomic)  UIImage * theImportantImage;

到我的.h文件,将图像设置为,然后我做了

theImportantFace.image=theImportantImage.

不确定为什么会起作用,但嘿,确实如此。看来我的问题与异步的东西根本没有关系。可怜。不满意不知道是什么问题。

答案 1 :(得分:0)

dispatch_xxx ...方法不调用任何东西。他们获取一段代码并将其添加到队列中。就像你在一张纸上写了一些说明并把那张纸放在同事的桌子上一样。你的同事将完成他正在做的任何事情,当他完成后,他将完成写在纸上的内容。

有一个特殊队列,称为"全局队列"。如果你把一张纸放在"全球"桌子上有五十个同事,他们中的任何一个都可以随时拿起那张纸,这样就可以更快完成工作(因为很多人都在从事不同的工作),但你永远都不知道他们的工作顺序是什么完成。

相关问题