繁体   English   中英

当我在滚动UITableview期间显示文档目录中的图像时,内存不断增加然后应用程序崩溃

[英]Memory continuously increase then app crash when i display image from document directory during scrolling UITableview

我的要求是下载应用程序内存中的所有图像,如果可用,则从本地显示。

下面是我从本地访问图像的代码,如果它不可用,那么它将下载然后显示。

[cell.imgProfilePic processImageDataWithURLString:cData.PICTURE];

我已经制作了自定义UIImageView

DImageView.h

    #import <UIKit/UIKit.h>
    @interface DImageView : UIImageView
    @property (nonatomic, strong) UIActivityIndicatorView *activityView;
    - (void)processImageDataWithURLString:(NSString *)urlString;
    + (UIImage *)getSavedImage :(NSString *)fileName;
    @end

DImageView.m

#import "DImageView.h"
#define IMAGES_FOLDER_NAME  @"DImages"

@implementation DImageView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {    }
    return self;
}
- (void)dealloc
{
    self.activityView = nil;
    [super dealloc];
}
- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self)
    {
        [self initWithFrame:[self frame]];
    }
    return self;
}
- (void)processImageDataWithURLString:(NSString *)urlString
{
    @autoreleasepool
    {
    UIImage * saveImg =[DImageView getSavedImage:urlString];
    if (saveImg)
    {
        @autoreleasepool
        {
        dispatch_queue_t callerQueue = dispatch_get_main_queue();
        dispatch_async(callerQueue, ^{

            @autoreleasepool{
            [self setImage:saveImg];
            }
        });
    }
    }
    else
    {
        [self showActivityIndicator];
        NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

        dispatch_queue_t callerQueue = dispatch_get_main_queue();
        dispatch_queue_t downloadQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH,0);
        __block NSError* error = nil;
        dispatch_async(downloadQueue, ^{

            @autoreleasepool
            {
                NSData * imageData = [NSData dataWithContentsOfURL:url options:NSDataReadingUncached error:&error];
                if (!error)
                {
                    dispatch_async(callerQueue, ^{
                        @autoreleasepool {
                        UIImage *image = [UIImage imageWithData:imageData];
                        [self setImage:image];
                        [self hideActivityIndicator];
                        [self saveImageWithFolderName:IMAGES_FOLDER_NAME AndFileName:urlString AndImage:imageData];
                        }
                    });
                }
            }
        });
        dispatch_release(downloadQueue);
    }
    }
}
- (void) showActivityIndicator
{
    self.activityView = [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
    self.activityView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin;
    self.activityView.hidesWhenStopped = TRUE;
    self.activityView.backgroundColor = [UIColor clearColor];
    self.activityView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;

    [self addSubview:self.activityView];
    [self.activityView startAnimating];
}
- (void) hideActivityIndicator
{
    CAAnimation *animation = [NSClassFromString(@"CATransition") animation];
    [animation setValue:@"kCATransitionFade" forKey:@"type"];
    animation.duration = 0.4;;
    [self.layer addAnimation:animation forKey:nil];
    [self.activityView stopAnimating];
    [self.activityView removeFromSuperview];

    for (UIView * view in self.subviews)
    {
        if([view isKindOfClass:[UIActivityIndicatorView class]])
            [view removeFromSuperview];
    }
}
- (void)saveImageWithFolderName:(NSString *)folderName AndFileName:(NSString *)fileName AndImage:(NSData *) imageData
{
    @autoreleasepool{
    NSFileManager *fileManger = [[NSFileManager defaultManager] autorelease];
    NSString *directoryPath =  [[NSString stringWithFormat:@"%@/%@",[DImageView  applicationDocumentsDirectory],folderName] autorelease];

    if (![fileManger fileExistsAtPath:directoryPath])
    {
        NSError *error = nil;
        [fileManger createDirectoryAtPath:directoryPath withIntermediateDirectories:YES attributes:nil error:&error];
    }
    fileName = [DImageView fileNameValidate:fileName];
    NSString *filePath = [[NSString stringWithFormat:@"%@/%@",directoryPath,fileName] autorelease];

    BOOL isSaved = [imageData writeToFile:filePath atomically:YES];
    if (!isSaved)DLog(@" ** Img Not Saved");
    }
}

+ (NSString *)applicationDocumentsDirectory
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
    return basePath;
}

+ (UIImage *)getSavedImage :(NSString *)fileName
{
    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
    fileName = [DImageView fileNameValidate:fileName];

    NSFileManager * fileManger = [[NSFileManager defaultManager] autorelease];
    NSString * directoryPath =  [[NSString stringWithFormat:@"%@/%@",[DImageView applicationDocumentsDirectory],IMAGES_FOLDER_NAME] autorelease];
    NSString * filePath = [[NSString stringWithFormat:@"%@/%@",directoryPath,fileName] autorelease];

    if ([fileManger fileExistsAtPath:directoryPath])
    {
        UIImage *image = [[[UIImage imageWithContentsOfFile:filePath] retain]autorelease];
        if (image)
            return image;
        else
            return nil;
    }
    [pool release];
    return nil;
}

+ (NSString*) fileNameValidate : (NSString*) name
{
    name = [name stringByReplacingOccurrencesOfString:@"://" withString:@"##"];
    name = [name stringByReplacingOccurrencesOfString:@"/" withString:@"#"];
    name = [name stringByReplacingOccurrencesOfString:@"%20" withString:@""];
    return name;
}
@end

一切正常,平滑滚动以及后台的asyncImage下载。

问题是当我滚动UITableview应用程序内存不断增加,经过一段时间后,我得到了Receive memory waring 2/3时间然后应用程序崩溃。

当我使用AsyncImageView类时,内存不会增加并且其工作正常。 但由于应用程序的要求,我将所有图像保存到Document Directory并在其可用时显示。

我已尝试使用@autoreleasepoolrelease一些变量但未获得成功。

我很感激,如果有人有解决方案来管理内存管理。

 **ARC is off in my application.** 

UIImagePNGRepresentation可能会返回非自动释放的对象 - 您可以尝试释放它并查看是否会导致崩溃。 显然你没有发布一些东西,但除了图像表示之外别无其他。

其他一些评论:

  • 使用ObjectAlloc工具在Instruments中运行您的应用程序,应该立即明确哪些对象未被释放。 如果您不了解乐器,那么现在是时候学习它了。

  • 您可以“跟踪”对象并在使用ObjectTracker解除分配时获取消息 - 但它是专为ARC设计的,因此您可能需要对其进行调整。 如果您使用它,您将在每个对象被释放时看到一条消息

  • 当表格视图使用单元格完成时,您可以接收一个委托方法,告诉您这样,然后您可以将单元格保留为nil(释放)和对象

  • 你使用downloadQueue是奇怪的 - 在你的实例中创建一次作为ivar,根据需要使用它,并在dealloc发布它

  • 您隐藏主队列上的活动微调器,但不要在主队列上启动它

  • 您命令活动视图从超级视图中删除自己,但随后在子视图中查找并尝试将其删除:

[self.activityView removeFromSuperview];

for (UIView * view in self.subviews)
{
    if([view isKindOfClass:[UIActivityIndicatorView class]])
        [view removeFromSuperview];
}

最后,仪器就是你想要的。 你可以在这里阅读更多关于它的信息,或者只是谷歌,你肯定会找到一大堆博客来阅读。

是的,最后我已经解决了。

问题中的代码现在正常工作。 但是如果没有release一些对象和代码中的@autoreleasepool块,在滚动UITableView期间内存会不断增加。

Instrument我发现UILableViewUIImageView中的内存增加。 我正在使用Custom UITableViewCell ,在该文件中我实现了dealloc方法。 所以当我在UITableViewCell .m文件中实现dealloc方法并releasenil all对象时。

在滚动TableView期间memory不增加并解决了问题。

根据我的理解,你的“getSavedImage”方法中存在一个问题,你必须手动管理内存而不是“自动释放”,所以我的建议是使用

UIImage *image = [[UIImage alloc] initWithContentsOfFile:filePath]
and also release it after use of it. means after '[self setImage:saveImg];'
[saveImg release]

而不是这个。

[[UIImage imageWithContentsOfFile:filePath] retain];

'不要使用Autorelease,因为它一直停留在内存中,直到池没有耗尽'而且正因为这样你才会遇到内存问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM