我有一张图片的URL(从UIImagePickerController获取),但是我不再拥有内存中的图片(该URL是从应用程序上一次运行中保存的)。我能够通过这个URL重新加载UIImage吗?
我看到UIImage有一个imageWithContentsOfFile:方法,但我有一个URL。我可以使用NSData的dataWithContentsOfURL:方法读取URL吗?
编辑1
根据@Daniel的答案,我尝试了以下代码,但它没有起作用...
NSLog(@"%s %@", __PRETTY_FUNCTION__, photoURL);
if (photoURL) {
NSURL* aURL = [NSURL URLWithString:photoURL];
NSData* data = [[NSData alloc] initWithContentsOfURL:aURL];
self.photoImage = [UIImage imageWithData:data];
[data release];
}
当我运行它时,控制台显示:
-[PhotoBox willMoveToWindow:] file://localhost/Users/gary/Library/Application%20Support/iPhone%20Simulator/3.2/Media/DCIM/100APPLE/IMG_0004.JPG
*** -[NSURL length]: unrecognized selector sent to instance 0x536fbe0
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSURL length]: unrecognized selector sent to instance 0x536fbe0'
查看调用堆栈,我调用了URLWithString,它又调用了URLWithString:relativeToURL:,然后是initWithString:relativeToURL:,然后是_CFStringIsLegalURLString,然后是CFStringGetLength,然后是forwarding_prep_0,然后是forwarding,最后是-[NSObject doesNotRecognizeSelector]。
有什么想法,为什么我的NSString(photoURL的地址是0x536fbe0)不响应length呢?为什么它说不响应-[NSURL length]?它难道不知道param是一个NSString而不是NSURL吗?
编辑2
好的,代码唯一的问题就在于字符串到URL的转换。如果我直接硬编码字符串,其他所有东西都能正常工作。所以我的NSString似乎有问题,如果我找不出原因,那么我猜这应该作为另一个问题提出。加入以下这行代码(我从上面的控制台日志中复制了路径),它可以正常工作:
photoURL = @"file://localhost/Users/gary/Library/Application%20Support/iPhone%20Simulator/3.2/Media/DCIM/100APPLE/IMG_0004.JPG";