0

I am showing around 50 Images In a scroll view and I am facing the memory issue, every time the Controller loads the memory usage increases and it goes over 200MB in the Instruments App.

.h file of my custom class #import

@class AnimalGrid;

@protocol AnimalGridViewDelegate <NSObject>
-(void)animalGrid:(AnimalGrid*)animalgridview tappedAtIndex:(int)index andName:(NSString*)animalName;
@end

@interface AnimalGrid : UIView

@property(nonatomic, strong)    UIImage         *animalImage;
@property(nonatomic, copy)      NSString        *animalName;
@property(nonatomic)    int        animalTag;

@property (nonatomic, assign)   id <AnimalGridViewDelegate> Delegate;

-(id)initGridWithFrame:(CGRect)frame andAnimalImage:(UIImage*)image andAnimalName:(NSString*)animalname andTag:(int)tag;
-(void)setFont:(UIFont*)font;
@end

.m file of my Custom Class

#import "AnimalGrid.h"

@implementation AnimalGrid
{
    UIImageView  *_contentView;
    UILabel      *_accessoryView;
    UIImage      *displayImage;
    NSString     *displayText;
}

@synthesize Delegate = _Delegate;

-(id)initGridWithFrame:(CGRect)frame andAnimalImage:(UIImage*)image andAnimalName:(NSString*)animalname andTag:(int)tag
{
    self = [super initWithFrame:frame];
    if (self) {

        self.backgroundColor = [UIColor clearColor];
        self.animalName = animalname;
        self.animalTag = tag;
        displayImage = image;
        displayText  = animalname;
        CGFloat contentHeight = frame.size.height * 0.8;

        if ( animalname == nil || animalname.length == 0)
            contentHeight = frame.size.height;

        CGFloat margin = 0;
        if (displayImage.size.height < contentHeight)
        {
            margin = contentHeight - displayImage.size.height;
        }


        UIView *placeholderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, frame.size.width, contentHeight)];
        placeholderView.backgroundColor = [UIColor clearColor];
        if (image.size.height > placeholderView.frame.size.height)
        {
            _contentView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, frame.size.width, placeholderView.frame.size.height)];
        }else if (image.size.height < placeholderView.frame.size.height){

            CGFloat margin = placeholderView.frame.size.height - image.size.height;
            _contentView = [[UIImageView alloc]initWithFrame:CGRectMake(0, margin, frame.size.width, placeholderView.frame.size.height - margin)];

        }

        _contentView.backgroundColor = [UIColor clearColor];
        _accessoryView = [[UILabel alloc]initWithFrame:CGRectMake(0, frame.size.height * 0.7, frame.size.width, frame.size.height-frame.size.height * 0.7)];
        _accessoryView.numberOfLines = 2;
        _accessoryView.backgroundColor = [UIColor clearColor];
        _accessoryView.font = [UIFont fontWithName:@"HFFAirApparent" size:23];
        _accessoryView.textColor = [UIColor orangeColor];

        [placeholderView addSubview:_contentView];
        [self addSubview:placeholderView];

        if ( animalname != nil || animalname.length > 0)
        [self addSubview:_accessoryView];

        if(image)
            _contentView.image = image;

        _contentView.contentMode = UIViewContentModeScaleAspectFit;
        _accessoryView.text = animalname;
        _accessoryView.numberOfLines = 0;
        [_accessoryView sizeToFit];

        CGFloat w = self.bounds.size.width/2;
        _accessoryView.frame = CGRectMake(w - (_accessoryView.frame.size.width/2), _accessoryView.frame.origin.y, _accessoryView.frame.size.width, _accessoryView.frame.size.height);

        UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapedOnImage:)];
        singleTap.numberOfTapsRequired = 1;
        singleTap.numberOfTouchesRequired = 1;

        [_contentView addGestureRecognizer:singleTap];
        _contentView.userInteractionEnabled = YES;
        self.userInteractionEnabled = YES;
    }

    return self;
}

-(void)setFont:(UIFont*)font
{
    _accessoryView.font = font;
}


-(void)tapedOnImage:(id)sender
{
    if ([_Delegate respondsToSelector:@selector(animalGrid:tappedAtIndex:andName:)]) {
        [_Delegate animalGrid:self tappedAtIndex:self.animalTag andName:self.animalName];
    }
}

@end

And this is how I am creating the Object of my custom class and showing them over Scroll View, In my Controller file I am using following methods

-(void)setGridAnimals
{
    @try {
        [self creatingGridsWithCompletion:^(BOOL done, NSMutableArray *arr)
         {
             for (int i = 0; i < arr.count; i++)
             {
                 UIView *gView = [arr objectAtIndex:i];
                 [gridScrollView addSubview:gView];
             }
             gridScrollView.scrollEnabled = YES;
             gridScrollView.pagingEnabled = YES;
             gridScrollView.bounces = YES;
             gridScrollView.contentSize = CGSizeMake(gridScrollView.frame.size.width, gridScrollView.frame.size.height*arr.count);
             [aView hideIndicatorView:YES];
         }];
    }
    @catch (NSException *exception) {
        NSLog(@" Exception is = %@ ",exception.description);
    }
    @finally {

    }


}


-(void)creatingGridsWithCompletion:(completionBlock)complete
{
    @autoreleasepool {
        NSMutableArray *pageArray = [NSMutableArray new];
        int rowcount = 3;
        int columncount = 5;

        CGFloat width = gridScrollView.frame.size.width/columncount - 5;
        CGFloat height = gridScrollView.frame.size.height/rowcount  - 5;

        int pagecount = gridAnimalArray.count/(rowcount*columncount);

        if (gridAnimalArray.count%(rowcount*columncount))
        {
            pagecount += 1;
        }
        //pagecount = 1;
        int x = 0;
        for (int i = 0; i < pagecount; i++)
        {
            UIView *page = [[UIView alloc]initWithFrame:CGRectMake(0, x, gridScrollView.frame.size.width, gridScrollView.frame.size.height)];
            for (int j = 0; j < rowcount; j++)
            {
                for (int k = 0; k < columncount; k++)
                {
                    int tag = (i*(rowcount*columncount))+(j*columncount)+k+1;
                    if (tag > gridAnimalArray.count)
                    {
                        break;
                    }
                    YEAnimal *animal = [gridAnimalArray objectAtIndex:tag-1];
                    NSString *name = [[animal.GridName componentsSeparatedByString:@"."] objectAtIndex:0];
                    UIImage *gridImg;
                    if ([[NSFileManager defaultManager]fileExistsAtPath:[[NSBundle mainBundle] pathForResource:name ofType:@"png"]])
                    {
                        NSString * imgpath= [ [ NSBundle mainBundle] pathForResource:name ofType:@"png"];
                        gridImg=[UIImage imageWithContentsOfFile: imgpath];
                    }else if ([[NSFileManager defaultManager]fileExistsAtPath:[[NSBundle mainBundle] pathForResource:name ofType:@"jpg"]])
                    {
                        NSString * imgpath= [ [ NSBundle mainBundle] pathForResource:name ofType:@"jpg"];
                        gridImg=[UIImage imageWithContentsOfFile: imgpath];
                    }

                    AnimalGrid *grid = [[AnimalGrid alloc]initGridWithFrame:CGRectMake((k * width)+5, (j*height), width, height) andAnimalImage:gridImg andAnimalName:animal.SpeciesName andTag:tag];
                    grid.backgroundColor = [self getColor];
                    [grid setDelegate:self];
                    [page addSubview:grid];
                }
            }

            [pageArray addObject:page];
            x += gridScrollView.frame.size.height;
        }

        complete(YES,pageArray);
    }
}

This is how the Grid Looks : http://s17.postimg.org/x9xdfl4j3/i_OS_Simulator_Screen_Shot_Mar_3_2015_1_54_45_P.png

So, far I came to know that I should use [UIImage imageWithContentsOfFile:] instead of [UIImage imageNamed:] to load the image, but still it does not help me.

Is there any way that I can free the Memory by releasing the ImageViews

Thanks.

1
  • Welcome to Stack Overflow. Loading 50 images should be expected to take that much RAM. Is there a specific issue that you are trying to solve? What have you tried? Mar 2, 2015 at 15:47

1 Answer 1

0

There are several aproaches possible, depending on the layout of your view. How does it look like?

However, you can use a table to display the pictures in or use a collection. Actually a collection is made for that.

If you want to stick with the scroll view, then these 50 views are hardly visible at once. You could actually set their images just before the each view comes into sight and remove the images (set .image to nil) when the view moves off screen.

An App that I made recenly it is designed in a way that only one and exactly one of the images is visible full screen. When the user scrolls its neighbour image comes into view. (paging mechanism) In my view the number of possible views is inpredictable. Although that is achievable with a collection too, I went for a scroll view. In that view I designed the hosting scroll view in a way that it is just large enough to hold three views. The middle view of them is visible on screen. (Which exceptions applied when the very first or last - if any - view is displayed). When the users scrolls just far enough for the neighbour view to be fully visible then I reset the scrollview so that its middle is visible again, move the view to the middle that just became visible, move the formerly visible view to the outer end and fill the other incoming end with a new view. That allows for endless scrolling with not need to hold more than 4 images in memory at once. (4: the one that just moved off, the two that are shifted within the scroll view and the new one are allocated within the same method at a time.)

2
  • Hi, I've added a link to show you how my grid looks, I've followed your instructions and now only loading visible Images to ScrollView and when user scrolls Up or Down I am removing the previous Objects and creating next set of Objects to show. This has surely reduced the Memory Pressure, but still memory usage increase every time that controller loads though the increment is very low. Mar 3, 2015 at 8:36
  • Now that you added the link to the layout I would suggest to go for a collection view instead. It comes with lot of the service that you need, e.g. it provides you with the option to re-use the cells (and therefore the images) and it cares for creating cells (and therefore images) only for those that are currently visible. Mar 4, 2015 at 9:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.