UITable, UINavigationController and AsyncImageView (iPhone)

Status
Not open for further replies.
The problem is that I have a nav controller which loads a table. Clicking on a cell pushes another table onto the navigator. Cicking on a cell in that table opens a detail view. Each of these has an image.

To keep the program from hanging, I made the image load asynchronously (http://www.markj.net/iphone-asynchronous-table-image/). This code creates a view with an image, but the image is initialized when the data is added, and so I just add the outer view to my cells.

Now, the trouble. When I load the first table, it never has any images. Sub-tables and detail views show them fine, but when I back up, the image in the cell whose details I was viewing disappears.

Now, code. Sorry that there's a lot of it, but I don't know how to make it more succinct.

I modified AsyncImageView a bit:

Code:
//
//  AsyncImageView.h
//  Postcard
//
//  Created by markj on 2/18/09.
//  Copyright 2009 Mark Johnson. You have permission to copy parts of this code into your own projects for any use.
//  www.markj.net
//


@interface AsyncImageView : UIView 
{
	//could instead be a subclass of UIImageView instead of UIView, depending on what other features you want to 
	// to build into this class?

	NSURLConnection* connection; //keep a reference to the connection so we can cancel download in dealloc
	NSMutableData* data; //keep reference to the data so we can collect it as it downloads
	//but where is the UIImage reference? We keep it in self.subviews - no need to re-code what we have in the parent class
	UIImageView* imageView;
}
-(void) setFrame:(CGRect) rect;
@end

Code:
#import "AsyncImageView.h"


// This class demonstrates how the URL loading system can be used to make a UIView subclass
// that can download and display an image asynchronously so that the app doesn't block or freeze
// while the image is downloading. It works fine in a UITableView or other cases where there
// are multiple images being downloaded and displayed all at the same time. 

@implementation AsyncImageView

- (id)initWithURL:(NSString*)urlAddr
{
	self = [super initWithFrame:CGRectZero];
	NSURL* url = [NSURL URLWithString:urlAddr];
	NSURLRequest* request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
	connection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 
	[connection retain];
	[self retain];
	return self;
}


//the URL connection calls this repeatedly as data arrives
- (void)connection:(NSURLConnection *)theConnection didReceiveData:(NSData *)incrementalData 
{
	if (data==nil)
	{ 
		data = [[NSMutableData alloc] initWithCapacity:2048]; 
	} 
	[data appendData:incrementalData];
}

//the URL connection calls this once all the data has downloaded
- (void)connectionDidFinishLoading:(NSURLConnection*)theConnection 
{
	//so self data now has the complete image 
	[connection release];
	connection=nil;
	if ([[self subviews] count] > 0)
	{
		//then this must be another image, the old one is still in subviews
		[[[self subviews] objectAtIndex:0] removeFromSuperview]; //so remove it (releases it also)
	}
	
	//make an image view for the image
	imageView = [[[UIImageView alloc] initWithImage:[UIImage imageWithData:data]] autorelease];
	//make sizing choices based on your needs, experiment with these. maybe not all the calls below are needed.
	imageView.contentMode = UIViewContentModeScaleAspectFit;
	imageView.autoresizingMask = ( UIViewAutoresizingFlexibleWidth || UIViewAutoresizingFlexibleHeight );
	[self addSubview:imageView];
	imageView.frame = self.bounds;
	UIView* v = imageView;
	while (v != nil)
	{
		[v setNeedsLayout];
		v = v.superview;
	}

	[data release]; //don't need this any more, its in the UIImageView now
	data=nil;
}

-(void) setFrame:(CGRect) rect
{
	[super setFrame:rect];
	imageView.frame = rect;
}

//just in case you want to get the image directly, here it is in subviews
- (UIImage*) image
{
	UIImageView* iv = [[self subviews] objectAtIndex:0];
	return [iv image];
}

- (void)dealloc 
{
	[connection cancel]; //in case the URL is still downloading
	[connection release];
	[data release]; 
    [super dealloc];
}
@end

A method in class Category. It holds data for the second table:

Code:
-(id* ) initWithName:(NSString* )nm andImg:(NSString* )imgU
{
	name = nm;
	[name retain];
	if (imgU != nil)
	{		
		img = [[AsyncImageView alloc] initWithURL:imgU];
		[img retain];
	}
	data = [NSMutableArray arrayWithCapacity:0];
	[data retain];
	return self;
}

The first table's cellForRowAtIndexPath:

Code:
- (UITableViewCell* )tableView:(UITableView* )tableView cellForRowAtIndexPath:(NSIndexPath* )indexPath
{
	UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:@"123"];
	
        if (cell == nil)
        {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"123"];
        }	
	
	Category* c = [xmlList objectAtIndex:indexPath.row];
	c.img.tag = 999;
	c.img.frame = CGRectMake(0, 5, 90, 90);
	[[cell.contentView viewWithTag:999] removeFromSuperview];
	[cell addSubview:c.img];
	
	UILabel* textLabel = [[UILabel alloc] initWithFrame: CGRectMake(100, 25, 0, 0)];
	[textLabel retain];
	textLabel.text = c.name;
	textLabel.font = [UIFont boldSystemFontOfSize:[UIFont labelFontSize]];
	[textLabel sizeToFit];
	[cell addSubview:textLabel];
	
	[cell retain];
	return cell;
}

(You might notice that my memory management is atrocious. I'm still mystified by it, so I just retain everything just in case.)
 

iBooks

Ars Centurion
274
Subscriptor
Tiiba":77kqunm8 said:
(You might notice that my memory management is atrocious. I'm still mystified by it, so I just retain everything just in case.)
I don't know about the rest of your code, but it made me go mad until I figured out and wrote down the following rules:
1) If you [[alloc] init] something, you need to [release] it later
2) If you use a convenience method (like NSURL* url = [NSURL URLWithString:urlAddr] ) then it will be autoreleased after it goes out of scope
3) If a method needs to return something that also needs to be released (like your UITableViewCell* cell) then you use autorelease

It's been a few months since I've done Objective-C, so I could be remembering these wrong... someone please correct me if I've gotten these wrong.
 

Ember

Ars Centurion
346
Subscriptor++
First of all I'd suggest you read Apples guides on Objective-C and memory management.
Superfluous retain leads to memory leak, and if an app leaks too much memory it'll be killed by OS.

Other than what iBooks pointed.

1) -[AsyncImageView initWithURL:]
you retain self. Never do this. It's already retained by [super init] (or +alloc, which one I'm not sure).

2) -[AsyncImageView setFrame:]
imageView.frame = rect; ==> imageView.frame = self.bounds;

3) -[AsyncImageView image]
Why don't use instance variable imageView?
And I'd recommend you don't autorelease imageView inside -connectionDidFinishLoading: and release it in -dealloc.

4) -[Category initWithName]
Why [img retain]? It's created by [[alloc] init].

It seems that the Category is a Model or a Controller in your app.
I think you'd better get rid of AsyncImageView and move the code loading image to Category and just use plain UIImageView.
If you set image property of UIImageView to nil, it doesn't show anything. No need to put it under useless view.
Please read documents about MVC pattern if you have not yet.

If you really think it's better to make a custom view, make it subclass of UIImageView and update image property as needed.
 
Ember, I'm not really getting what you're saying, sorry. I tried making the async view a subclass of UIImageView, but it didn't help. That's all I understood, but I don't understand the rationale. Also, it seems that the images actually don't get downloaded at all for the main table. I put a breakpoint in didReceiveData, and it never gets hit.

Also, because it wouldn't be right if something just fucking worked, I have a file I want to load at runtime. I use:
Code:
[NSData dataWithContentsOfFile:@"(file name)"];
and get nil. I tried putting the file in all sorts of directories, and the result is the same.
 

Ember

Ars Centurion
346
Subscriptor++
First, I haven't checked if your AsyncImageView is correctly loading the image or not, as I don't have experience handling async URL loading myself.
I just pointed the errors breaking basic Obj-C and Cocoa rules.

Anyway a few more comments.

The current working directory of the process may not be the directory the bundled data reside.
Assuming the image file is part of the app - if you added it to the Xcode project - to load data from file "AnImage.png".
Code:
    NSString *image_path = [[NSBundle mainBundle] pathForResource:@"AnImage" ofType:@"png"];
    NSData *image_data = [NSData dataWithContentsOfFile:image_path];
Also when you handle data files generated or loaded, you should specify correct directory/path.

Look up NSSearchPathForDirectoriesInDomains() from the Xcode's Developer Documentation. It's used to find the ~/Documents folder and other standard folders.
And NSString provides many methods that handle file paths and URLs. Such as +pathWithComponents:, -pathComponents, -pathExtension and -stringByAppendingPathComponent:.

If the delegate method -connection:didReceiveData: is not called, you'd better set a breakpoint at -initWithURL: and see whether it's called and the request is properly initiated with correct URL.

But I recommend you make sure that it works fine with local/bundled image before tackling the async-loading problem.
 

topham

Ars Legatus Legionis
13,756
Subscriptor
Code:
imageView.autoresizingMask = ( UIViewAutoresizingFlexibleWidth || UIViewAutoresizingFlexibleHeight );

should be

Code:
imageView.autoresizingMask = ( UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight );

I suspect the code you cribbed it from is UITables with Downloaded Images; the code isn't perfect. You should break it down and rebuild it to understand it all. As well there is a comment which refers to a specific issue in iOS4 about images failing to load initially.
 
Status
Not open for further replies.