所以我有一个应用程序下载和解析一些JSON提要与一些网址。每个请求只下载4个URL。每个网址都是图片网址,我正在尝试显示每个网址。下一个按钮将显示下一个按钮,同时保持前面的按钮可见。异步下载的iPad图像
当我运行我的应用程序时,它有时会起作用,有时它不会。我收到一个EXEC_BAD_ACCESS
错误。此外,我相信这不是下载图像的最佳/最有效的方式(即使你是我异步做它)。
这是我如何做到这一点。我非常感谢任何有关如何更改我的应用程序以更有效地下载图像的设计建议/建议。
在我的ViewController,我有以下方法:
- (void)imageSearchController:(id)searchController gotResults:(NSArray *)results {
AsyncUIImage *imageDownload;
for (int i = 0; i < [results count]; i++) {
imageDownload = [[AsyncUIImage alloc] init];
// Grab the image data in a dictionary
NSDictionary *dictionary = [NSDictionary dictionaryWithDictionary:[results objectAtIndex:i]];
// Grab the values in an array
NSArray *values = [NSArray arrayWithArray:[dictionary allValues]];
// Get the image's URL in a string - strings at index 3
NSString *url = [NSString stringWithString:[values objectAtIndex:3]];
imageDownload.delegate = self;
[imageDownload downloadImageFromURL:url];
[imageDownload release];
}
}
这种方法是作为JSON饲料已下载了,即会调用的方法(使用NSURLConnection的 - 这是委托方法)。它会创建一个AsyncUIImage
对象,然后将每个图像的URL传递给该对象以进行下载和显示。
我的AsyncUIImage
类是处理图像下载的对象。它有以下几种方法:
首先,开始下载如下方法:
- (void)downloadImageFromURL:(NSString *)url {
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:url]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
// create the connection with the request
// and start loading the data
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection) {
// Create the NSMutableData to hold the received data.
// receivedData is an instance variable declared elsewhere.
data = [[NSMutableData data] retain];
}
else {
NSLog(@"error in connection");
[theConnection release];
}
}
再平常NSURLConnection
委托方法。该connectionDidFinishLoading:
方法如下:
- (void)connectionDidFinishLoading:(NSURLConnection *)theConnection {
self.image = [UIImage imageWithData:data];
[self.delegate imageDidLoad:self.image];
}
此方法通知的图像已经被下载委托方法。所以回的ViewController,即imageDidLoad
委托方法将显示图片如下:
- (void)imageDidLoad:(UIImage *)image {
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(xOffset, yOffset, 192, 192)];
imageView.image = image;
[imageView release];
[self.view addSubview:imageView];
xOffset = xOffset + 192;
if (count != 0 && count % 4 == 0) {
yOffset = yOffset + 192;
xOffset = 0;
}
count++;
}
我没有从编程经验& iOS的体验与iOS平台上的异步下载丰富的经验,但是,我相信,我所做的有一些重大缺陷。
有没有人有任何意见/建议?任何反馈都非常感谢。
谢谢。
首先:请让我们知道是什么行会导致'EXEC_BAD_ACCESS'错误。 –
您应该检查这个问题:http://stackoverflow.com/questions/7567827/last-in-first-out-stack-with-gcd因为最好的方法,使你想使用大中央调度什么。 – 3lvis
是的,我有一本书,我很快就会学习GCD,但我没有时间坐下来学习它。 – darksky