所以我有一個應用程序下載和解析一些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