I need to laod a image from NSMutableArray which is loaded from service url.I can retrieve the image tag from XML response.Now I want that image in a UITableViewCell
My array looks like this :
(
{
Image="46b6daca-3.png";
}
{
Image="9251bfe5-d.jpg";
}
)
How can I load each image in a seperate UITableViewCell ?
For creating a UILabel I knew it is like this :
NSMutableDictionary *d = (NSMutableDictionary *) [arr objectAtIndex:indexPath.row];
UILabel *line1=[[UILabel alloc]initWithFrame:CGRectMake(10, 68, 320,10)];
line1 .font=[UIFont fontWithName:#"arial" size:12];
[line1 setTextAlignment:UITextAlignmentLeft];
[line1 setText:[d valueForKey:#"Name"]];
line1.tag=113;
[cell addSubview:line1 ];
[line1 release];
How can I do it for UIImage?
UIImageView *img = [[UIImageView alloc]initWithImage:[ d objectForKey:#"Image"]];
[cell.contentView addSubView:img];
as per you code.. try this.
NSMutableDictionary *d = (NSMutableDictionary *) [arr objectAtIndex:indexPath.row];
UIImageView *img = [[UIImageView alloc]initWithImage:[ d objectForKey:#"Image"]];
img,frame = CGRectMake("Set frame")]
[cell.contentView addSubView:img];
[img release];
if you have images in your array then use direct array value as a image like bellow..
UIImageView *img = [[UIImageView alloc]initWithImage:[[arrData valueForKey:#"Image"] objectAtIndex:indexPath.row];
img.frame = SetFrameHere;//
[cell.contentView addSubView:img];
or also add as a cell imageview like bellow..
cell.imageView.image = (UIImage *)[[arrData valueForKey:#"Image"] objectAtIndex:indexPath.row];
Use the following code for setting the image:
UIImage *img = [[UIImage imageNamed:[d objectForKey:#"Image"];
cell.imageView.image = img;
Here d is your NSMutableDictionary
Related
I have two UIImageView and two textfiled under the image view. One textfield for image1 and second textfield for image2.
Now I want that user enter text and give image name and that image will save in document directory in .rtf format. And the when I open .rtf I will be able to edit that rtf.
imageView = [[UIImageView alloc] initWithFrame:CGRectMake(100,50, 100, 100)];
[imageView setImage:[UIImage imageNamed:#"image1.png"]];
self.view addSubview:imageView];
[imageView release];
imageView1 = [[UIImageView alloc] initWithFrame:CGRectMake(100,150, 100, 100)];
[imageView1 setImage:[UIImage imageNamed:#"image2.png"]];
self.view imageView1];
[imageView1 release];
txt=[[UITextField alloc]initWithFrame:CGRectMake(5,190, 180, 30)];
txt.backgroundColor=[UIColor whiteColor];
txt.placeholder=#"Enter Text";
txt.textColor = [UIColor blackColor];
txt.delegate =self;
[txt addTarget:self action:#selector(ImageSave_method) forControlEvents:UIControlEventEditingDidEnd];
txt.textAlignment=NSTextAlignmentCenter;
txt.userInteractionEnabled = YES;
txt.autocapitalizationType = NO;
txt.font=[UIFont fontWithName:#"Helvetica" size:15];
[self.view addSubview:txt];
txt2=[[UITextField alloc]initWithFrame:CGRectMake(200,190, 180, 30)];
txt2.backgroundColor=[UIColor whiteColor];
txt2.placeholder=#"Enter Text";
txt2.textColor = [UIColor blackColor];
txt2.delegate =self;
[txt2 addTarget:self action:#selector(ImageSave_method) forControlEvents:UIControlEventEditingDidEnd];
txt2.textAlignment=NSTextAlignmentCenter;
txt2.userInteractionEnabled = YES;
txt2.autocapitalizationType = NO;
txt2.font=[UIFont fontWithName:#"Helvetica" size:15];
[self.view addSubview:txt2];
I have no idea how to do this.
Any Idea or suggestion would be highly welcome.
you can use the nsuserdefaults to saved the image name
NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
[userDefault setObject:_imageName1 forKey:#"imageName1"];
[userDefault setObject: _imageName2 forKey:#"imageName2"];
[userDefault synchronize];
for retrieving the data from nsuserdefaults
NSUserDefaults *userDefault=[NSUserDefaults standardUserDefaults];
NSString *_imageName1 = [userDefault objectForKey:#"imageName1"];
NSString *_imageName2 = [userDefault objectForKey:#"imageName2"];
to save the image in documents directory
create the file path
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES) objectAtIndex:0];
NSString *imagePath1 = [NSString stringWithFormat:#"%#/imageName1.png",
docDir];
convert the UIImage into nsdata
NSData *data = UIImagePNGRepresentation(myImage.image);
then save the image into imagePath1 of document directory
[data writeToFile:imagePath1 atomically:YES];
for retrieving the image
UIImage *img = [UIImage imageWithContentsOfFile:imagePath1];
As TableView cell labels are displayed on load but when the tableView is scrolled the tableview contents are not appearing. But if I select any of the cell then the labels in that particular cell are displaying.
Please help me. I have the same problem in different aspect too. I did not get any resolution for it.
Here is my code of cellForRowAtIndexPath method:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
static NSString *CellIdentifier = #"newsTableCell";
UITableViewCell *cell = [self.newsTable dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil) {
cell =[[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
UILabel *user = [[UILabel alloc] initWithFrame:CGRectMake(84, 10,75,21)];
user.tag = 101;
[cell.contentView addSubview:user];
[user release];
UILabel *usr = (UILabel *)[cell viewWithTag:101];
usr.font = [UIFont boldSystemFontOfSize:12.0];
[usr setText:[appDelegate.usernames objectAtIndex:[indexPath row]]];
UILabel *status = [[UILabel alloc] initWithFrame:CGRectMake(154,10,69,21)];
status.tag = 102;
[cell.contentView addSubview:status];
[status release];
status = (UILabel *)[cell viewWithTag:102];
status.font = [UIFont boldSystemFontOfSize:12.0];
[status setText:[appDelegate.statistics objectAtIndex:[indexPath row]]];
UILabel *rival = [[UILabel alloc] initWithFrame:CGRectMake(220,10,80,21)];
rival.tag = 103;
[cell.contentView addSubview:rival];
[rival release];
UILabel *rivals = (UILabel *)[cell viewWithTag:103];
rivals.font = [UIFont boldSystemFontOfSize:12.0];
[rivals setText:[appDelegate.rivalusernames objectAtIndex:[indexPath row]]];
UILabel *gamename = [[UILabel alloc] initWithFrame:CGRectMake(84,27,208,21)];
gamename.tag = 104;
[cell.contentView addSubview:gamename];
[gamename release];
UILabel *gamenames = (UILabel *)[cell viewWithTag:104];
gamenames.font = [UIFont boldSystemFontOfSize:12.0];
[gamenames setText:[appDelegate.challengenames objectAtIndex:[indexPath row]]];
UILabel *time = [[UILabel alloc] initWithFrame: CGRectMake(84,47,149,21)];
time.tag = 105;
[cell.contentView addSubview:time];
[time release];
UILabel *times = (UILabel *)[cell viewWithTag:105];
times.font = [UIFont boldSystemFontOfSize:12.0];
[times setText:[appDelegate.remainingtime objectAtIndex:[indexPath row]]];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(12,10,67,58)];
imageView.tag = 106;
[cell.contentView addSubview:imageView];
[imageView release];
NSURL *url = [NSURL URLWithString:[appDelegate.imagepaths objectAtIndex:[indexPath row]]];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *img = [[UIImage alloc] initWithData:data];
UIImageView *imgView = (UIImageView *)[cell viewWithTag:106];
imgView.image = img;
return cell;
}
first of all move these lines inside the if (cell==NIL):
if(cell == nil) {
cell =[[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
UILabel *user = [[UILabel alloc] initWithFrame:CGRectMake(84, 10,75,21)];
user.tag = 101;
[cell.contentView addSubview:user];
[user release];
}
or you add a subview to the cell each time you reuse it, scrolling
and the same for:
UILabel *status = [[UILabel alloc] initWithFrame:CGRectMake(154,10,69,21)];
status.tag = 102;
[cell.contentView addSubview:status];
[status release];
and
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(12,10,67,58)];
imageView.tag = 106;
[cell.contentView addSubview:imageView];
[imageView release];
...etc etc
as a general rule: you add/alloc new objects just once when you first create a cell (inside the if (cell==nil))
then outside that if you just reuse all objects and change their properties, as text of image source...
Maybe the color of your UILabels is the same as the background color? When you select a cell and then you can see the text, it probably is because of the then highlighted cell color ...
And I also strongly suggest you make a cell subclass as cortez mentioned, this code is not read- nor maintainable ...
your implementation of the UITableView Cell is rong try this way
i Know your problem will solve.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
static NSString *CellIdentifier = #"newsTableCell";
UITableViewCell *cell = [self.newsTable dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil)
{
cell =[[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
UILabel *user = [[UILabel alloc] initWithFrame:CGRectMake(84, 10,75,21)];
user.tag = 101;
usr.font = [UIFont boldSystemFontOfSize:12.0];
[cell.contentView addSubview:user];
[user release];
UILabel *status = [[UILabel alloc] initWithFrame:CGRectMake(154,10,69,21)];
status.tag = 102;
status.font = [UIFont boldSystemFontOfSize:12.0];
[cell.contentView addSubview:status];
[status release];
UILabel *rival = [[UILabel alloc] initWithFrame:CGRectMake(220,10,80,21)];
rival.tag = 103;
[cell.contentView addSubview:rival];
[rival release];
}
else
{
UILabel *usr = (UILabel *)[cell viewWithTag:101];
status = (UILabel *)[cell viewWithTag:102];
rival = (UILabel *)[cell viewWithTag:103];
}
[usr setText:[appDelegate.usernames objectAtIndex:[indexPath row]]];
[status setText:[appDelegate.statistics objectAtIndex:[indexPath row]]];
[rival setText:[appDelegate.statistics objectAtIndex:[indexPath row]]];
return cell;
}
Initially I written the code as above. After the suggestion of meronix I have changed to below one. Please suggest.
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
if (tableView.tag ==16)
{
NSLog(#"%d",appDelegate.checkChallenges);
static NSString *CellIdentifier = #"newsTableCell";
UITableViewCell *cell = [self.newsTable dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil) {
cell =[[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
UILabel *user = [[UILabel alloc] initWithFrame:CGRectMake(84, 10,75,21)];
user.tag = 101;
[cell.contentView addSubview:user];
[user release];
UILabel *status = [[UILabel alloc] initWithFrame:CGRectMake(154,10,69,21)];
status.tag = 102;
[cell.contentView addSubview:status];
[status release];
UILabel *rival = [[UILabel alloc] initWithFrame:CGRectMake(220,10,80,21)];
rival.tag = 103;
[cell.contentView addSubview:rival];
//[rival release];
UILabel *gamename = [[UILabel alloc] initWithFrame:CGRectMake(84,27,208,21)];
gamename.tag = 104;
[cell.contentView addSubview:gamename];
[gamename release];
UILabel *time = [[UILabel alloc] initWithFrame: CGRectMake(84,47,149,21)];
time.tag = 105;
[cell.contentView addSubview:time];
[time release];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(12,10,67,58)];
imageView.tag = 106;
[cell.contentView addSubview:imageView];
[imageView release];
}
UILabel *usr = (UILabel *)[cell viewWithTag:101];
usr.font = [UIFont boldSystemFontOfSize:12.0];
[usr setText:[appDelegate.usernames objectAtIndex:[indexPath row]]];
UILabel *stat = (UILabel *)[cell viewWithTag:102];
stat.font = [UIFont boldSystemFontOfSize:12.0];
[stat setText:[appDelegate.statistics objectAtIndex:[indexPath row]]];
NSURL *url = [NSURL URLWithString:[appDelegate.imagepaths objectAtIndex:[indexPath row]]];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *img = [[UIImage alloc] initWithData:data];
UIImageView *imgView = (UIImageView *)[cell viewWithTag:106];
imgView.image = img;
UILabel *times = (UILabel *)[cell viewWithTag:105];
times.font = [UIFont boldSystemFontOfSize:12.0];
[times setText:[appDelegate.remainingtime objectAtIndex:[indexPath row]]];
UILabel *gamenames = (UILabel *)[cell viewWithTag:104];
gamenames.font = [UIFont boldSystemFontOfSize:12.0];
[gamenames setText:[appDelegate.challengenames objectAtIndex:[indexPath row]]];
UILabel *rivals = (UILabel *)[cell viewWithTag:103];
rivals.font = [UIFont boldSystemFontOfSize:12.0];
[rivals setText:[appDelegate.rivalusernames objectAtIndex:[indexPath row]]];
return cell;
}
My app is scrolling very slow when I have Images set for each cell. I have tried using the SDImageWeb Project, but it still scrolls just as slow, and all the image views on the cell end up getting stretched around. Here is my code in the cell at row.
- (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];
}
RSSEntry *entry = [_allEntries objectAtIndex:indexPath.row];
//root path of image...used to check if image exists for this article
NSString *substring = #"http://316apps.com/ipreachersblog/wp";
NSRange textRange = [entry.articleImage rangeOfString:substring];
if(textRange.location != NSNotFound){
NSString *thearticleImage = entry.articleImage;
NSRegularExpression *expression = [NSRegularExpression regularExpressionWithPattern:#"(?i)\\b((?:[a-z][\\w-]+:(?:/{1,3}|[a-z0-9%])|www\\d{0,3}[.]|[a-z0-9.\\-]+[.][a-z]{2,4}/)(?:[^\\s()<>]+|\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\))+(?:\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\)|[^\\s`!()\\[\\]{};:'\".,<>?«»“”‘’]))" options:NSRegularExpressionCaseInsensitive error:NULL];
NSString *someString = thearticleImage;
NSString *oneurl = [someString substringWithRange:[expression rangeOfFirstMatchInString:someString options:NSMatchingCompleted range:NSMakeRange(0, [someString length])]];
NSURL *picimage = [NSURL URLWithString:oneurl];
UIFont *cellFont = [UIFont fontWithName:#"ArialRoundedMTBold" size:15];
UIFont *cellFont2 = [UIFont fontWithName:#"ArialRoundedMTBold" size:12];
NSData * urlData = [NSData dataWithContentsOfURL: picimage];
UIImage * imageweb = [UIImage imageWithData: urlData];
CGSize newSize = CGSizeMake(69, 69);
UIGraphicsBeginImageContext( newSize );
[imageweb drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
CALayer * l = [cell.imageView layer];
[l setMasksToBounds:YES];
[l setCornerRadius:11];
[l setBorderWidth:2.0];
[l setBorderColor:[[UIColor blackColor] CGColor]];
cell.textLabel.text = entry.articleTitle;
cell.textLabel.font = cellFont;
cell.detailTextLabel.font = cellFont2;
cell.imageView.image = newImage;
cell.imageView.contentMode = UIViewContentModeScaleAspectFill;
}
else {
//loads when no featured image present
}
return cell;
}
Any ideas?
The problem is here
NSURL *picimage = [NSURL URLWithString:oneurl];
UIFont *cellFont = [UIFont fontWithName:#"ArialRoundedMTBold" size:15];
UIFont *cellFont2 = [UIFont fontWithName:#"ArialRoundedMTBold" size:12];
NSData * urlData = [NSData dataWithContentsOfURL: picimage];
UIImage * imageweb = [UIImage imageWithData: urlData];
CGSize newSize = CGSizeMake(69, 69);
UIGraphicsBeginImageContext( newSize );
[imageweb drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
CALayer * l = [cell.imageView layer];
[l setMasksToBounds:YES];
[l setCornerRadius:11];
[l setBorderWidth:2.0];
[l setBorderColor:[[UIColor blackColor] CGColor]];
For every time you scroll the view 3 cells are downloading the images. Here you are resizing images which is not recommended
You need to set image in Lazy load like this
[cell.imageView setImageWithURL:picimage placeholderImage:[UIImage imageNamed:#"loadingPicture.png"]];
and every thing will be taken care by this. you can get this by importing this SDImageCache class, it will be available in this sample code at here
You are downloading the image from a remote source, so each time you load a new cell, the image gets downloaded and that will slow your application down, apple has a sample project on how to load the image asynchronously
hi i am working on UITableView custom cell for twitter, for each cell i am adding UIImageView(userPhoto), UILabel(name), UILabel(tweet), UILabel(Data), This i have to dealloc all elements,
please go through the attached Image of INSTRUMENT TOOL alloc screen shot
when i run the Instrument tool, it showing some are not dealloc, how to dealloc,
this is my code
//Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *identifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if(!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewStyleGrouped reuseIdentifier:nil];
//cell.selectionStyle = UITableViewCellSelectionStyleNone;
UILabel *name = [[UILabel alloc]initWithFrame:CGRectMake(72,3,242,15)] ;
name.text = (NSString*)[(Tweet*)[tweetArray objectAtIndex:indexPath.row] userName];
[name setFont:[UIFont fontWithName:#"Helvetica" size:13]];
name.textColor=[UIColor colorWithRed:250 green:250 blue:210 alpha:0.5];
[name setBackgroundColor:[UIColor clearColor]];
UILabel *date = [[[UILabel alloc]initWithFrame:CGRectMake(200,3,130,15)] autorelease];
date.text = (NSString*)[(Tweet*)[tweetArray objectAtIndex:indexPath.row] created_at];
[date setFont:[UIFont fontWithName:#"Helvetica" size:12]];
date.textColor=[UIColor colorWithRed:250 green:250 blue:210 alpha:0.5];
[date setBackgroundColor:[UIColor clearColor]];
UILabel * tweetLabel = [[UILabel alloc]initWithFrame:CGRectMake(72,20,242,60)] ;
tweetLabel.text = (NSString*)[(Tweet*)[tweetArray objectAtIndex:indexPath.row] tweet];
tweetLabel.numberOfLines = 3;
tweetLabel.textColor=[UIColor colorWithRed:252 green:148 blue:31 alpha:1];
[tweetLabel setFont:[UIFont fontWithName:#"Helvetica" size:12]];
[tweetLabel setBackgroundColor:[UIColor clearColor]];
UIImageView *myImage = [[UIImageView alloc]initWithFrame:CGRectMake(6,10,58,60)] ;
NSURL *url = [NSURL URLWithString:[(Tweet*)[tweetArray objectAtIndex:indexPath.row] image_url]];
NSData *data = [NSData dataWithContentsOfURL:url];
[myImage setImage: [UIImage imageWithData:data]];
[cell.contentView addSubview:myImage];
[cell.contentView addSubview:tweetLabel];
[cell.contentView addSubview:name];
[cell.contentView addSubview:date];
[myTweetActivityIndicator stopAnimating];
[myTweetActivityIndicator setHidesWhenStopped:YES];
return cell;
}
please guide me
Thank you
You can use
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewStyleGrouped reuseIdentifier:nil] autorelease];
For other labels, you can probably use
[date release]; [tweetLabel release]; [name release]; [myImage release];
You'll have to send a release message to all the objects that you have allocated using init/alloc (name, date, tweetLabel, myImage) as soon as you're finished with them (for example, after addSubview). Note that according to the documentation, the view is retained by the receiver.
try using
NSData *data = [[NSData alloc] initWithContentsOfURL:url];
[myImage setImage: [UIImage imageWithData:data]];
[data release];
data = nil;
In this case, we are manually releasing the memory allocated. I hope, this works
I've released my app and noticed the jerkyness when scrolling in the CellForRowAtIndexPath, this is because i'm rendering an image from an JSON Feed via a URL. I've searched the internet and found a few examples and this one i've almost got working. The problem is when it renders the images don't match the correct title. Can someone please have a look and see what if i'm doing something obviously wrong.
Anyway here is my code:
- (void)displayImage:(UIImage *)image {
[photo setImage:image];
}
-(void)loadImage:(NSString *)url {
NSData* imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:url]];
UIImage* image = [[[UIImage alloc] initWithData:imageData] autorelease];
[imageData release];
[self performSelectorOnMainThread:#selector(displayImage:) withObject:image waitUntilDone:NO];
}
CellForRowAtIndexPath Methord
#define DATELABEL_TAG 1 #define MAINLABEL_TAG 2 #define PHOTO_TAG 3 UIImageView *photo;
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *MainNewsCellIdentifier = #"MainNewsCellIdentifier";
UILabel *mainLabel, *dateLabel;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: MainNewsCellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier: MainNewsCellIdentifier] autorelease];
cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
dateLabel = [[[UILabel alloc] initWithFrame:CGRectMake(15.0,15.0,170.0,15.0)] autorelease];
dateLabel.tag = DATELABEL_TAG;
dateLabel.font = [UIFont systemFontOfSize:10.0];
dateLabel.textAlignment = UITextAlignmentLeft;
dateLabel.textColor = [UIColor darkGrayColor];
dateLabel.autoresizingMask = UIViewAutoresizingFlexibleRightMargin;
[cell.contentView addSubview:dateLabel];
mainLabel = [[[UILabel alloc] initWithFrame:CGRectMake(15.0,28.0,170.0,60.0)] autorelease];
mainLabel.tag = MAINLABEL_TAG;
mainLabel.font = [UIFont boldSystemFontOfSize:14.0];
mainLabel.textColor = [UIColor blackColor];
mainLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleRightMargin;
mainLabel.numberOfLines = 0;
[cell.contentView addSubview:mainLabel];
photo = [[[UIImageView alloc] initWithFrame:CGRectMake(190.0,15.0,85.0,85.0)] autorelease];
photo.tag = PHOTO_TAG;
photo.contentMode = UIViewContentModeScaleAspectFit;
[cell.contentView addSubview:photo];
}
else {
dateLabel = (UILabel *)[cell.contentView viewWithTag:DATELABEL_TAG];
mainLabel = (UILabel *)[cell.contentView viewWithTag:MAINLABEL_TAG];
photo = (UIImageView *)[cell.contentView viewWithTag:PHOTO_TAG];
}
NSUInteger row = [indexPath row];
NSDictionary *stream = (NSDictionary *) [dataList objectAtIndex:row];
NSString *title = [stream valueForKey:#"title"];
NSString *titleString = #"";
if( ! [title isKindOfClass:[NSString class]] )
{
titleString = #"";
}
else
{
titleString = title;
}
CGSize maximumSize = CGSizeMake(180, 9999);
UIFont *dateFont = [UIFont fontWithName:#"Helvetica" size:14];
CGSize dateStringSize = [titleString sizeWithFont:dateFont
constrainedToSize:maximumSize
lineBreakMode:mainLabel.lineBreakMode];
CGRect dateFrame = CGRectMake(15.0, 28.0, 170.0, dateStringSize.height);
mainLabel.frame = dateFrame;
mainLabel.text = titleString;
dateLabel.text = [stream valueForKey:#"created"];
NSString *i = [NSString stringWithFormat:#"http://www.domain.co.uk/images/stories/%#", [stream valueForKey:#"image"]];
photo.image = [UIImage imageNamed:#"i_digital_media.png"];
NSOperationQueue *queue = [NSOperationQueue new];
NSInvocationOperation *operation = [[NSInvocationOperation alloc]
initWithTarget:self
selector:#selector(loadImage:)
object:i];
[queue addOperation:operation];
[operation release];
return cell;}
By the time that your image is loaded, the photo variable is pointed to a different photo :)
You need to pass both the loaded image and the UIImageView you want to update back - try using a NSDictionary to pass variables between threads :
- (void)displayImage:(NSDictionary *)info {
[[info objectForKey:#"photo"] setImage:[info objectForKey:#"image"]];
}
-(void)loadImage:(NSDictionary *)info {
NSString *imagePath = [info objectForKey:#"imagePath"];
UIImageView *photo = [info objectForKey:#"photo"];
// Load the image
NSData* imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:url]];
UIImage* image = [[[UIImage alloc] initWithData:imageData] autorelease];
[imageData release];
// Pass it back to the main thread
NSDictionary *mainThreadInfo = [NSdictionary dictionaryWithObjectAndKeys:image, #"image", photo, #"photo", nil];
[self performSelectorOnMainThread:#selector(displayImage:) withObject:mainThreadInfo waitUntilDone:YES];
}
so now, your operation will pass the photo and the image data back to the main thread. Create the operation like this :
NSDictionary *info = [NSDictionary dictionaryWithObjectsAndKeys:i, #"imagePath", photo, #"photo", nil];
NSInvocationOperation *operation = [[NSInvocationOperation alloc]
initWithTarget:self
selector:#selector(loadImage:)
object:info];
And get rid of the global photo variable :)