因此,我有一个应用程序,它可以下载并解析带有一些URL的JSON提要。每个请求仅下载4个URL。每个URL都是一个图像URL,我尝试显示每四个URL。“下一步”按钮将显示接下来的四个,同时保持前一个可见。
当我运行我的应用程序时,它有时起作用,有时不起作用。我得到一个EXEC_BAD_ACCESS错误。此外,我认为这不是下载图像的最好/最有效的方式(即使是thougH我也是异步下载的)。
这就是我是怎么做的。我将非常感谢任何关于我应该如何更改我的应用程序以更有效地下载图像的设计意见/建议。
在我的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经验来看,我认为我所做的事情有一些重大缺陷。
有没有人有什么想法/建议?任何反馈都是非常感谢的。
谢谢。
发布于 2011-11-05 12:11:33
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(xOffset, yOffset, 192, 192)];
imageView.image = image;
[imageView release];
[self.view addSubview:imageView];当您将imageView传递给addSubview:时,它已经被释放。您需要在将其添加为self.view的子视图后将其释放。
如果你用谷歌搜索objective-c内存管理,你会发现很多初学者指南可以帮助你理解retain和release。
发布于 2011-11-05 12:17:18
也许这不是你想要的答案,但我已经使用了这个库:HJCache我做了一个twitter客户端应用程序,我自己的异步图像下载实现也给我带来了很多问题。
在更改到这个库之后,一切都很顺利,如果您想要添加额外的功能或其他什么,也可以对其进行修改。
它还可以让你缓存你的图像,并且在一个表格视图上同时下载多个图像是没有问题的。
https://stackoverflow.com/questions/8018096
复制相似问题