1

我有一个奇怪的问题。要求是在滑动时从 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;

//下载图片.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 的其他代表已实现,但我没有把它放在这里。返回此图像后,我将此图像设置为滚动视图并显示它并从滚动视图中删除前一个图像。

更多信息:-

只是为了验证我注释掉了将图像设置为滚动视图并在每次滑动时下载了图像但它仍然崩溃了大约 30 个图像

令人惊讶的是,我使用同一个类 DownloadImage.h 和 .m 在同一工作的其他地方下载图像,即使使用 500images 也能正常工作。

我正在 iPod Touch 中进行测试,我检查了使用的内存保持在 12-14mb 之间(永远不要超过这个)

请帮助我,如果您需要更多详细信息,请告诉我。

4

1 回答 1

1

它崩溃是因为所有图像都存储在虚拟内存中,您需要缓存它们,然后在用户实际查看它们时将它们加载回内存。

尝试在缓存或不需要图像对象后将它们设置为 nil。

在您的课程中,我还建议使用 didReceiveMemoryWarning 方法,并在调用此方法时从内存中释放一些图像。

于 2013-03-08T10:55:45.963 回答