Memory not being released for UICollectionView of large images - memory-management

I have an NSMutableArray of 15 elements, all of them strings. The strings refer to an image name that is stored locally in the app (images approximately 640x640 each). I am displaying the array of images in a UICollectionView.
When I reload the collectionView to display the images, my memory usage shoots up as you would expect displaying large png's (though its footprint is much larger than I expected).
The real problem is that memory used by these images is never freed. So despite me removing all objects from the array, removing the collectionView and setting everything to nil, none of the memory is freed.
Why is this? I would expect my memory to return to it's original level if I removed these objects and removed the ViewController.
UPDATED: Code snippet
ViewController.m
#implementation ViewController
static NSString *CellIdentifier = #"photoCell";
-(void)viewDidLoad{
[super viewDidLoad];
self.photoCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0,0, self.view.frame.size.width, 320) collectionViewLayout:self.photoSpringFlowLayout];
[self.photoCollectionView setDataSource:self];
[self.photoCollectionView setDelegate:self];
[self.view addSubview:self.photoCollectionView];
[self.photoCollectionView registerClass:[PhotoPreviewCell class] forCellWithReuseIdentifier:CellIdentifier];
self.imagesAray = [[NSMutableArray alloc] initWithObjects:#"photo1", #"photo2", #"photo3", #"photo4", #"photo5", #"photo6", #"photo7", #"photo8", #"photo9", #"photo10", #"photo11", #"photo12", #"photo13", #"photo14", #"photo15", nil];
[self.photoCollectionView reloadData];
}
#pragma mark - UICollectionView Methods
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return self.imagesArray.count;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
PhotoPreviewCell *cell = (PhotoPreviewCell*)[collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
NSString *imageName = self.imagesArray[indexPath.row];
[cell.photoImage setImage:[UIImage imageNamed:imageName]];
return cell;
}
PhotoPreviewCell.m
#implementation PhotoPreviewCell
-(id)initWithFrame:(CGRect)frame{
self = [super initWithFrame:frame];
if(self){
self.photoImage = [[UIImageView alloc] init];
self.photoImage.frame = CGRectMake(0, 0, 160, 160);
self.photoImage.contentMode = UIViewContentModeScaleAspectFit;
[self.contentView addSubview:self.photoImage];
}
return self;
}

Ok so the reason for this is that loading images from flash takes some time and OS tries to avoid loading it on and on, so it's caching loaded images. They're cached only when you're using imageNamed: method. If you're testing on simulator release all objects and try simulate memory warning. This should force OS to remove not used images from cache.

Related

Switched from tableview to colelctionview now didselectitematindexpath not called

So I switched from a UITableView to a UICollectionView. The cells are all loading just fine and look beautiful, but now I can no longer select any of them. The taps are recognized in the logs, but it doesn't take me to the view that it's supposed to take me to anymore.
The only things that changed really are the ones the ones you see commented out in the "cellForItem" section. Everything else is identical to how it was when it was working in the TableView. It's just supposed to take me to the ViewController specified when you tap. Instead the tap is recorded, but it does nothing. Any help would be appreciated.
Also I tried getting rid of the [collectionView deselectItemAtIndexPath:indexPath animated:YES];
...but it didn't make any difference.
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
PlaceCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
// Configure the cell
//UINib * placeCell = [UINib nibWithNibName:#"Shops" bundle:nil];
// NSArray *topLevelItems = [placeCell instantiateWithOwner:self options:nil];
// cell = [topLevelItems objectAtIndex:0];
Place *p = [_entries objectAtIndex:indexPath.row];
cell.placeName.text = p.PName;
NSLog(#"p:%#",p.PName);
cell.placeName.textColor = [UIColor colorWithRed:3/255.0f green:6/255.0f blue:4/255.0f alpha:1.0f];
NSString *pIcon;
pIcon = typeName;
//NSLog(pIcon);
cell.placeImg.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:p.PImage]]];
NSLog(#"i:%#",p.PImage);
return cell;
}
-(void) collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
NSLog(#"Tap Recognized");
[collectionView deselectItemAtIndexPath:indexPath animated:YES];
Place *p = [_entries objectAtIndex:indexPath.row];
DetailPlaceViewController * pvc = [[DetailPlaceViewController alloc] init];
[pvc setPlace:p];
[self.navigationController pushViewController:pvc animated:YES];
}
Well this one was fun...
For some odd reason my navigation controller isn't working... so of course using the navigation controller to load a view wasn't going to work. Simple enough solution... load the view without the navigation controller. I was just going to delete this question, but maybe somebody might be in a similar situation one day:
[self presentViewController:pvc animated:YES completion:nil];

Memory Warning in UICollectionView (with image)

I am currently working on a UICollectionView with a lot of images. However, it sometimes crashes in this view with memory warning. I am using AFNetworking and UIImageView+AFNetworking category to set image through setImageWithURL: method. One issue can be caching. I am not sure if AFNetworking deals with image caching. Anyway, is there a way to optimize this code in terms of memory management? Or if I am to implement didReceiveMemoryWarning method in this view controller, what can be put in this method? I attach the code for cellForItemAtIndexPath for this collection view.
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"RecipeCell" forIndexPath:indexPath];
// setting the image view for the cell using AFNetworking. Does this do caching automatically?
UIImageView *recipeImageView = (UIImageView *)[cell viewWithTag:6];
if (PRODUCTION) {
[recipeImageView setImageWithURL:[[self.recipes objectAtIndex:indexPath.row] objectForKey:#"recipe_image"] placeholderImage:[UIImage imageNamed:#"default_recipe_picture.png"]];
} else {
[recipeImageView setImageWithURL:[NSString stringWithFormat:#"http://localhost:5000/%#", [[self.recipes objectAtIndex:indexPath.row] objectForKey:#"recipe_image"]] placeholderImage:[UIImage imageNamed:#"default_recipe_picture.png"]];
}
// configure the back of the cell. fill all the info.
UITextView *recipeNameView = (UITextView *)[cell viewWithTag:8];
recipeNameView.text = [NSString stringWithFormat:#"%#", [[self.recipes objectAtIndex:indexPath.row] objectForKey:#"recipe_name"]];
UILabel *recipeNameLabel = (UILabel *)[cell viewWithTag:2];
recipeNameLabel.text = [NSString stringWithFormat:#"%#", [[self.recipes objectAtIndex:indexPath.row] objectForKey:#"recipe_name"]];
NSDictionary *user = [[self.recipes objectAtIndex:indexPath.row] objectForKey:#"user"];
UIButton *chefNameButton = (UIButton *)[cell viewWithTag:3];
[chefNameButton setTitle:[NSString stringWithFormat:#"%# %#", [user objectForKey:#"first_name"], [user objectForKey:#"last_name"]] forState:UIControlStateNormal];
NSMutableArray *missingIngredientsStringArray = [[NSMutableArray alloc] init];
NSArray *missingIngredients = [[self.recipes objectAtIndex:indexPath.row] objectForKey:#"missing_ingredients"];
for (NSDictionary *missingIngredient in missingIngredients) {
[missingIngredientsStringArray addObject:[missingIngredient objectForKey:#"name"]];
}
NSString *missingIngredientsString = [missingIngredientsStringArray componentsJoinedByString:#","];
UITextView *missingIngredientsView = (UITextView *)[cell viewWithTag:4];
missingIngredientsView.text = [NSString stringWithFormat:#"%u Missing Ingredients: %#", missingIngredients.count, missingIngredientsString];
// configure the front of the cell. chef name button and missing ingredients and likes on front view
UIButton *frontNameButton = (UIButton *)[cell viewWithTag:11];
[frontNameButton setTitle:[NSString stringWithFormat:#"%# %#", [user objectForKey:#"first_name"], [user objectForKey:#"last_name"]] forState:UIControlStateNormal];
[frontNameButton sizeToFit];
frontNameButton.frame = CGRectMake(160 - [frontNameButton.titleLabel.text sizeWithFont:[UIFont boldSystemFontOfSize:13]].width - 7, frontNameButton.frame.origin.y, frontNameButton.frame.size.width, frontNameButton.frame.size.height);
UILabel *likesLabel = (UILabel *)[cell viewWithTag:9];
likesLabel.text = [NSString stringWithFormat:#"%# likes", [[self.recipes objectAtIndex:indexPath.row] objectForKey:#"likes"]];
UIButton *missingIngredientsButton = (UIButton *)[cell viewWithTag:12];
[missingIngredientsButton setBackgroundImage:[UIImage imageNamed:#"badge_green.png"] forState:UIControlStateSelected];
if (missingIngredients.count == 0) {
missingIngredientsButton.selected = YES;
[missingIngredientsButton setTitle:#"" forState:UIControlStateNormal];
} else {
missingIngredientsButton.selected = NO;
[missingIngredientsButton setTitle:[NSString stringWithFormat:#"%u", missingIngredients.count] forState:UIControlStateNormal];
}
// make back view invisible.
UIView *backView = [cell viewWithTag:1];
UIView *frontView = [cell viewWithTag:5];
frontView.alpha = 1.0;
backView.alpha = 0;
// adding flip gesture recognizers
UIView *flipView1 = [cell viewWithTag:12];
UIView *flipView2 = [cell viewWithTag:1];
UITapGestureRecognizer *flipGestureRecognizer1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(flipCell:)];
UITapGestureRecognizer *flipGestureRecognizer2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(flipCell:)];
[flipView1 addGestureRecognizer:flipGestureRecognizer1];
[flipView2 addGestureRecognizer:flipGestureRecognizer2];
return cell;
}
[Edit] I attach a screenshot of my Instruments run.
You can see that memory allocation increases as I just push segue and press back button repeatedly. Things that just keep increasing are CFData, CALayer, CABackingStore, UITableView. I doubt these are things that are created after segue, and they are not being released... Please help!
You're probably going to want some sort of image caching strategy to avoid re-downloading images. And UIImageView+AFNetworking category does cache images for you. But you may also have the responses being cached in the in-memory URL cache, which in this case is somewhat redundant.
So you might consider reducing or turning off the in-memory URL cache. I had the issue you're describing and the following reduced my memory issues quite a bit:
NSURLCache *sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:0 diskCapacity:0 diskPath:nil];
[NSURLCache setSharedURLCache:sharedCache];
AFNetworking automatically stores images in an NSCache collection, which automatically removes some or all of the images from memory on a low memory warning. AFNetworking is probably not your issue.
In fact, I don't think displaying images is your issue unless you're downloading lots of very large images and displaying them simultaneously. (If this is the case, you should try optimizing your images for display on the device so they don't need to be resized.)
One issue I see is that you are adding a gesture recognizer to the cell every time it comes into the view, but cells are reused, so when a cell comes in again you are adding unnecessary gesture recognizers to it. You could resolve this by subclassing UITableViewCell and assigning the gesture recognizers as properties. You could also resolve this by checking flipView1 and flipView2 to see if they have gesture recognizers attached before adding them. (I'm not sure if this is enough to cause a memory warning though.)
I'd recommend going to Build -> Profile and selecting the Allocations instrument. On the left, select Objective C only, and hide system calls. Then, scroll through your collection view and look at the instrument to see what's taking up all the memory.
UPDATE
Here's a screenshot of the Allocations tool:

Simple UICollectionView to show images behaves odd: Some Images are displayed correct, some at wrong position, some missing at all

I want to show images in a grid on iPhone using a UICollectionView, showing 3 images a row. For a "dead simple test" (as I thought), I've added 15 JPG images to my project, so that they'll be in my bundle and I can load them simply via [UIImage imageNamed:...].
I think I've done everything correct (setting up & registering UICollectionViewCell subclass, use of UICollectionViewDataSource Protocol methods), however, the UICollectionView behaves very weird:
It shows only a few of the images in the following pattern:
First line shows image 1 & 3, second line is blank, next line like the first again (image 1 & 3 showing properly), fourth line blank, and so on...
If I push a button in my NavBar that triggers [self.collectionView reloadData], random cells appear or disappear. What drives me nuts is that it's not only an issue of images appear or not. Sometime, images also swap between the cells, i.e. they appear for a indexPath they are definitely not wired up!
Here is my code for the cell:
#interface AlbumCoverCell : UICollectionViewCell
#property (nonatomic, retain) IBOutlet UIImageView *imageView;
#end
#implementation AlbumCoverCell
#synthesize imageView = _imageView;
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
_imageView = [[UIImageView alloc] initWithFrame:frame];
[self.contentView addSubview:_imageView];
}
return self;
}
- (void)dealloc
{
[_imageView release];
[super dealloc];
}
- (void)prepareForReuse
{
[super prepareForReuse];
self.imageView.image = nil;
}
#end
Part of the code for my UICollectionViewController subclass, where 'imageNames' is an NSArray holding all jpg filenames:
- (void)viewDidLoad
{
[super viewDidLoad];
[self.collectionView registerClass:[AlbumCoverCell class] forCellWithReuseIdentifier:kAlbumCellID];
}
#pragma mark - UICollectionViewDataSource Protocol methods
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return [self.imageNames count];
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
AlbumCoverCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kAlbumCellID forIndexPath:indexPath];
NSString *imageName = [self.imageNames objectAtIndex:indexPath.row];
NSLog(#"CV setting image for row %d from file in bundle with name '%#'", indexPath.row, imageName);
cell.imageView.image = [UIImage imageNamed:imageName];
return cell;
}
#pragma mark - UICollectionViewDelegateFlowLayout Protocol methods
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath;
{
return CGSizeMake(100, 100);
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section;
{
return UIEdgeInsetsMake(0, 0, 0, 0);
}
From the NSLog statement in cellForItemAtIndexPath: I can see that the method is called for all of the cells (not only the one's displayed) and that the mapping between indexPath.row and filename is correct.
Has anybody an idea what could cause this weird behavior?
In the meantime, I've found the solution. It was actually a very subtle error in the implementation of my UICollectionViewCell subclass AlbumCoverCell.
The problem is that I've set the frame of the cell instance as the frame of the UIImageView subview instead of passing the bounds property of the cell's contentView!
Here is the fix:
#implementation AlbumCoverCell
#synthesize imageView = _imageView;
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// WRONG:
// _imageView = [[UIImageView alloc] initWithFrame:frame];
// RIGHT:
_imageView = [[UIImageView alloc] initWithFrame:self.contentView.bounds];
[self.contentView addSubview:_imageView];
}
return self;
}
- (void)prepareForReuse
{
[super prepareForReuse];
// reset image property of imageView for reuse
self.imageView.image = nil;
// update frame position of subviews
self.imageView.frame = self.contentView.bounds;
}
...
#end

Showing Activity indicator while loading sqlite local database

I have a local SQLite Database and need to return a large number of records. It takes a several seconds to load so I want to add an activity indicator. The activity indicator seems to be running as it should but the problem is the pool isn't allowing the arrays to return any value see below.
- (void)viewDidLoad
{
[super viewDidLoad];
activityIndicator = [[[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
activityIndicator.frame = CGRectMake(0.0, 0.0, 48.0, 48.0);
activityIndicator.center = self.view.center;
[self.view addSubview:activityIndicator];
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
[activityIndicator startAnimating];
[self performSelectorInBackground:#selector(loadData) withObject:nil];
}
//What I need to load from SQLITE
-(void)loadData {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // Path to the database
//CODED HERE FOR DATABASE TO OPEN AND QUERY HERE TO BUILD ARRAYS
NSString *firstField = [NSString stringWithUTF8String:cFirst];
NSString *secondField = [NSString stringWithUTF8String:cSecond];
NSString *thirdField = [NSString stringWithUTF8String:cThird];
[FirstArray addObject:firstField];
[SecondArray addObject:secondField];
[ThirdArray addObject:thirdField];
//Checking to see if records are being added to the arrays
NSString *recordAdded = [NSString stringWithFormat:#"%# - %# - %#", firstField, secondField, thirdField];
NSLog(#"Song: %#", recordAdded);
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
[activityIndicator stopAnimating];
[pool release];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
NSString *firstValue = [firstArray objectAtIndex:indexPath.row];
NSString *secondValue = [secondArray objectAtIndex:indexPath.row];
NSString *thirdValue = [thirdArray objectAtIndex:indexPath.row];
NSString *details = [NSString stringWithFormat:#"%# - %#", secondValue, thirdValue];
cell.textLabel.text = cellValue;
cell.detailTextLabel.text = details ;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
When I'm looking at the debugger I see that the arrays are being built as the activity indicator is going. The problem is that I think the pool release is releasing my arrays too.
The code returns the query in the table view fine when I don't add the Pool and activity indicator.
Can anyone help to point me in the right direction to not release the arrays if that's what is happening here? Any kind of help would be much appreciated. :-)
---Also---
After looking around more I found that I have to pass the arrays back to the main thread. This is what I gather from searching online.
[self performSelectorOnMainThread:#selector(done:) withObject:cellData waitUntilDone:NO];
How would I go about loading the table with these arrays?
Not sure about your pool releasing the array, your code seems pretty direct. You may want to check whether you are really getting any data from your database.
However, I notice that you stop animating the activity indicator in the background thread. UI activity should be done in the main thread. I just did this coding last night and solved my problem using this thread. Put your stop animating code in the selector specified by performSelectorOnMainThread.
The strings are fine because they are being added to the array.
It looks like your array is being released, but you don't show the code for it.
How are you creating the array itself? If it is autoreleased, it will be deallocated when you drain the pool. You should "retain" it instead of "auotrelease"ing it.
Try to add [tableview reloadData] at the end of the -(void)loadData method

Xcode table view reload continually adds data to the table

I have an rss parser as part of my app code, and it is working fine and loading the rss xml file and populating the tableview fine.
The problem is with a refresh/reload button, which does reload the rss data, but it APPENDS the new data to the table and the table just grows and grows in size.
What the behaviour should do is to clear the old table data and rebuild the table with the new data - so that the table always shows just ONE set of data and doesn't keep growing every time the reload/refresh is pressed.
The table build code is as follows:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
int storyIndex = [indexPath indexAtPosition: [indexPath length] - 1];
cell.textLabel.text = [[stories objectAtIndex: storyIndex] objectForKey: #"date"];
cell.detailTextLabel.text = [[stories objectAtIndex: storyIndex] objectForKey: #"title"];
[cell.textLabel setLineBreakMode:UILineBreakModeWordWrap];
[cell.textLabel setNumberOfLines:0];
[cell.textLabel sizeToFit];
[cell.detailTextLabel setLineBreakMode:UILineBreakModeWordWrap];
[cell.detailTextLabel setNumberOfLines:0];
[cell.detailTextLabel sizeToFit];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
And the reload/refresh button code is:
- (void)reloadRss {
UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
UIBarButtonItem * barButton = [[UIBarButtonItem alloc] initWithCustomView:activityIndicator];
[[self navigationItem] setLeftBarButtonItem:barButton];
[barButton release];
[activityIndicator release];
[activityIndicator startAnimating];
[self performSelector:#selector(parseXMLFileAtURL) withObject:nil afterDelay:0];
[newsTable reloadData];
}
I have tried to solve this by adding the line:
if (stories) { [stories removeAllObjects]; }
to the reload section, which I think should work and does clear the table, but the app then crashes the app with an EXC_BAD_ACCESS.
Any ideas or suggestions greatly appreciated!
Actually, have now solved this!
Was due to "autoreleasing" elements of the array, so after clearing this out, they were invalid.
Removing autorelease and just releasing these objects in the final dealloc worked.
The Code EXC_BAD_ACCESS does mean, that you want connect at a variable that does not exists anymore.
In your code example, I can see, the problem to see at the following two lines of code:
[activityIndicator release];
[activityIndicator startAnimating];
You release the activityIdicator befor starting the Animating.
Try to release at the end of the function.
[activityIndicator startAnimating];
[self performSelector:#selector(parseXMLFileAtURL) withObject:nil afterDelay:0];
[newsTable reloadData];
[activityIndicator release];

Resources