1

我正在通过 ItunesU 上的斯坦福课程,他们说下载内容的线程不应该对 UI 做任何事情,这应该只发生在主线程上。

好吧,在我的示例中,我正在从 Flicker 下载一张图片,并且我想将这张图片(通过 segue)设置在UIScrollView. 因此,当我在“侧面”线程中下载这张图片时,我正在设置图像的图像属性UIScrollview等。但这显然不起作用,因为我还不知道图像大小,我也不知道对该图像对象的引用尚未正确设置?

那你怎么处理呢?我希望我很清楚..这是我的例子:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(NSIndexPath *)sender{
NSDictionary *selectedPhoto = [self.photos objectAtIndex:sender.row];

    [self.defaults addPhotoToRecentlyViewed:selectedPhoto];
    [self.defaults saveDefaults];

    PhotoViewer *photoViewer = segue.destinationViewController;

    UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    photoViewer.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:spinner];
    [spinner startAnimating];

    dispatch_queue_t photoDownload = dispatch_queue_create("photoviewever", nil);

    dispatch_async(photoDownload, ^{        
        NSData *data = [NSData dataWithContentsOfURL:[FlickrFetcher urlForPhoto:selectedPhoto format:FlickrPhotoFormatLarge]];
        UIImage *image = [UIImage imageWithData:data];
        photoViewer.image = image;

        dispatch_async(dispatch_get_main_queue(), ^{

            photoViewer.title = [selectedPhoto objectForKey:FLICKR_PHOTO_TITLE];
            photoViewer.navigationItem.rightBarButtonItem = nil;
        });
    });
}

和我的照片查看器:

#import "PhotoViewer.h"

@interface PhotoViewer ()

@property (nonatomic, strong) IBOutlet UIScrollView *scrollView;
@property (nonatomic, strong) IBOutlet UIImageView *imageView;

@end

@implementation PhotoViewer

@synthesize scrollView = _scrollView;
@synthesize imageView = _imageView;
@synthesize image = _image;

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.scrollView.delegate = self;
    [self setupImage];
}

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
    return self.imageView;
}

- (void)setupImage{
    self.imageView.image = self.image;
    self.imageView.frame = CGRectMake(0, 0, self.image.size.width, self.image.size.height);
    self.scrollView.contentSize = self.image.size;
    [self.imageView setNeedsDisplay];
}

@end
4

1 回答 1

0

你应该移动这一行:

        photoViewer.image = image;

进入你分派回主线程的“完成”块。PhotoViewer 似乎是一个视图控制器,因此它受制于与其他 UI 相同的“仅主线程”规则。此外,您似乎需要-setupImage从该主线程“完成”块再次调用。(否则,图像将永远不会被推送到图像视图中,如您所述。)

同样在 中-setupImage,您想self.image在寻址到它之前检查它是否返回一个非零值。根据您使用的编译器,调用返回结构的Objective C 方法的行为是“未定义的”(即self.image.size 返回一个CGSize 结构)。(尽管在最近的编译器中,它返回一个零填充结构。

于 2013-01-12T17:10:14.950 回答