[英]iphone memory issue while downloading images
我有一個奇怪的問題。 要求是從滑動時從URL下載圖像並在圖像視圖中顯示它。一切正常,但在30張圖像以及幾次滑動應用崩潰后,我收到內存警告。
實施非常簡單,但是已經花了將近2天的時間來解決問題。 每次滑動我都會調用A方法:-
-(void)callDownloadImageAPI{
NSAutoreleasePool *pool=[[NSAutoreleasePool alloc] init];
[self loadIndicator:@"Please Wait.!!" :@"Please be patient while we are downloading image for you"];
@try{
DownloadImage *downLoadImge =[[DownloadImage alloc] init];
downLoadImge.delegate=self;
[downLoadImge getImage:[self.allUrlArray objectAtIndex:self.initialImageViewCounter]];
}
@catch (NSException *e) {
NSLog(@"callDownloadImageAPI exception %@",[e description]);
[HUD hide:YES];
}
[pool release];
}
此方法一次下載1張圖片,然后將UIImage發送給它的委托
//DownloadImage.h和.m的實現
@protocol DownloadImageDelegate
@required
- (void)messageFormServerWithImage:(UIImage*)imageFromSever;
- (void)gettingImageFailed :(NSString*)errorDesc;
@end
@interface DownloadImage : NSObject
@property(strong) NSURLConnection* connection;
@property(weak) id<DownloadImageDelegate> delegate;
@property(strong) NSMutableData* data;
-(void)getImage:(NSString *)imageUrl;
//DownloadImage.m
-(void)getImage:(NSString *)imageUrl{
@autoreleasepool {
[[NSURLCache sharedURLCache] removeAllCachedResponses];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:imageUrl]cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60];
self.connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
}
- (void)connectionDidFinishLoading:(NSURLConnection*)theConnection {
@autoreleasepool {
NSLog(@"connectionDidFinishLoading");
self.connection=nil;
if( self.data == nil) {
return;
}
// NSString* jsonStr = [[NSString alloc] initWithData:self.data encoding:NSASCIIStringEncoding];
UIImage *img=[UIImage imageWithData:self.data];
// NSArray *messages_json = [parser objectWithString:jsonStr error:nil];
[self.delegate messageFormServerWithImage:img];
self.data = nil;
img= nil;
}
}
NSUrlConnections的其他委托已實現,但我不在這里了。 返回此圖像后,我將其設置為scrollview並顯示它,並從scrollview中刪除先前的圖像。
更多信息:-
只是為了驗證我已將設置圖像注釋掉為scrollview,並且每次滑動僅下載了圖像,但仍然崩潰了約30張圖像
出乎意料的是,我使用同一類DownloadImage.h和.m在同一工作中的其他位置下載圖像,即使使用500images,它也很棒。
我正在iPod Touch中進行測試,我檢查了所使用的內存是否保持在12-14mb之間(請不要超過此值)
請幫幫我,如果您需要更多詳細信息,請告訴我。
它崩潰是因為所有圖像都存儲在虛擬內存中,您需要對其進行緩存,然后在用戶實際查看它們時將其重新加載到內存中。
嘗試將已緩存或不需要的圖像對象也設置為nil。
在您的課程中,我還建議您使用didReceiveMemoryWarning方法,並在調用該方法時從內存中釋放一些圖像。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.