Why does my tableview break at the 4th entry? - iphone

This is the code I have. It works fine for the first 3 entries, then on the 4th entry, it starts showing the same cell content as other cells, despite the height of each cell being correct. Can anybody spot any problems that i'm not seeing here? The cell.textLabel.text is there purely for testing purposes, and comes back as the correct cell number, even if the contents of the cell aren't right. Since it's set at the same time as the content, this leads me to believe the problem is not in cellForRowAtIndexPath.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
JCell *cell = (JCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
UIImageView *imageView;
if (cell == nil) {
cell = [[JCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
imageView = [[UIImageView alloc] init];
imageView.contentMode = UIViewContentModeCenter;
[cell addSubview:imageView];
}
UIImage *image = [self.mediaDelegate largeThumbnailForMediaAtIndex:indexPath.row];
imageView.frame = CGRectMake(0, IMAGE_SPACING, image.size.width, image.size.height);
imageView.image = image;
imageView.center = CGPointMake(cell.bounds.size.width / 2, imageView.center.y);
cell.textLabel.text = [NSString stringWithFormat:#"%i", indexPath.row];
return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
int mediaHeight = [self.mediaDelegate heightForLargeThumbnailForMediaAtIndex:indexPath.row];
return mediaHeight + (IMAGE_SPACING * 2);
}
It's always going to be a JImage, because i haven't started on movie support yet.
-(UIImage *)largeThumbnailForMediaAtIndex:(int)index
{
id media = [self.media objectAtIndex:index];
if ([media isKindOfClass:[JImage class]]) {
JImage *image = media;
return [image getLargeThumbnail];
}
else if ([media isKindOfClass:[JMovie class]]) {
JMovie *movie = media;
return [movie getLargeThumbnail];
}
else {
return nil;
}
}
-(UIImage *)getLargeThumbnail {
if (self.largeThumbnail == nil) {
UIImage *originalImage = [UIImage imageWithContentsOfFile:self.originalImage];
UIImage *resizedImage = [originalImage imageScaledToFitSize:LARGE_THUMBNAIL_SIZE];
self.largeThumbnail = #"Generating";
dispatch_queue_t myQueue = dispatch_queue_create("LargeThumbnailQueue", 0);
dispatch_async(myQueue, ^{
NSString *filePath = [JImage writeImageToFile:resizedImage];
self.largeThumbnail = filePath;
});
return resizedImage;
}
else if ([_largeThumbnail isEqualToString:#"Generating"]) {
UIImage *originalImage = [UIImage imageWithContentsOfFile:self.originalImage];
UIImage *resizedImage = [originalImage imageScaledToFitSize:LARGE_THUMBNAIL_SIZE];
return resizedImage;
}
else {
NSString *filePath = self.largeThumbnail;
UIImage *image = [UIImage imageWithContentsOfFile:filePath];
return image;
}
}
+(NSString *)writeImageToFile:(UIImage *)image {
NSData *fullImageData = UIImageJPEGRepresentation(image, 1.0);
NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents/Images/"];
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL isDirectory = NO;
BOOL directoryExists = [fileManager fileExistsAtPath:path isDirectory:&isDirectory];
if (directoryExists) {
} else {
[fileManager createDirectoryAtPath:path withIntermediateDirectories:NO attributes:nil error:nil];
}
NSString *retinaSupport;
if ([[UIScreen mainScreen] respondsToSelector:#selector(scale)] && [[UIScreen mainScreen] scale] == 2){
retinaSupport = #"#2x";
}
NSString *name = [NSString stringWithFormat:#"%#%#.jpg", [JMedia generateUuidString], retinaSupport];
NSString *filePath = [path stringByAppendingPathComponent:name];
[fullImageData writeToFile:filePath atomically:YES];
return filePath;
}
Any assistance or help with this problem is greatly appreciated.

when you reuse a cell (ie. you don't enter if (cell == nil) you don't have an imageView. imageView will be nil.
Add a tag to retrieve that imageView when you reuse your cells:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
JCell *cell = (JCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
UIImageView *imageView;
if (cell == nil) {
cell = [[JCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
imageView = [[UIImageView alloc] init];
imageView.contentMode = UIViewContentModeCenter;
imageView.tag = 1234;
[cell addSubview:imageView];
}
imageView = [cell viewWithTag:1234];
UIImage *image = [self.mediaDelegate largeThumbnailForMediaAtIndex:indexPath.row];
imageView.frame = CGRectMake(0, IMAGE_SPACING, image.size.width, image.size.height);
imageView.image = image;
imageView.center = CGPointMake(cell.bounds.size.width / 2, imageView.center.y);
cell.textLabel.text = [NSString stringWithFormat:#"%i", indexPath.row];
return cell;
}

Shouldn't you rather do
UIImage *image = [self.mediaDelegate largeThumbnailForMediaAtIndex:indexPath.row];
cell.imageView.frame = CGRectMake(0, IMAGE_SPACING, image.size.width, image.size.height);
cell.imageView.image = image;
cell.imageView.center = CGPointMake(cell.bounds.size.width / 2, imageView.center.y);
?
(or at least, you should retrieve the imageView from the cell and not use what it looks to be a instance variable)

You're only allocating imageView to the cell if it goes into the
if (cell == nil)
block. So after the tableview has created a couple of instances, it will reuse them and you won't get an imageView added to it.
EDIT:
UIImageView *imageView; <------------ imageView is nil
if (cell == nil) {
cell = [[JCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
imageView = [[UIImageView alloc] init];
imageView.contentMode = UIViewContentModeCenter;
[cell addSubview:imageView];
}
UIImage *image = [self.mediaDelegate largeThumbnailForMediaAtIndex:indexPath.row];
// At this point, imageView is still nil - not been initialised to anything
imageView.frame = CGRectMake(0, IMAGE_SPACING, image.size.width, image.size.height);
imageView.image = image;
imageView.center = CGPointMake(cell.bounds.size.width / 2, imageView.center.y);

Related

UITableViewCell(s) with default image overwritten with other images upon scrolling

Oops,I am facing an issue with table view cells having no image,i.e. the cell with default image.Upon scrolling the default image disappears and some image from a cell is appearing on it.I have implemented the suggestion from Mr.Rckoenes here .Even then I was unable to fix the issue.Here is my implementation code for understanding:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
ReminderClass *reminderToDisplay = [self.remindersArray objectAtIndex:indexPath.row];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier];
// Now create the cell to display the data
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kCellIdentifier] autorelease];
cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
cell.textLabel.numberOfLines = 0;
cell.textLabel.font = [UIFont fontWithName:kHelvetica size:17.0];
cell.textLabel.adjustsFontSizeToFitWidth = YES;
cell.backgroundColor = [UIColor clearColor];
}
......
if (Image != nil)
{
UIImageView *imageView=[[UIImageView alloc] initWithFrame:CGRectMake(240, 3, 70, 63)];
imageView.backgroundColor=[UIColor clearColor];
[imageView setImage:Image];
cell.accessoryView = imageView;
[imageView release];
}
else
{
UIImageView *imageView=[[UIImageView alloc] initWithFrame:CGRectMake(240, 3, 70, 63)];
imageView.backgroundColor=[UIColor clearColor];
UIImage *defaultImage = [UIImage imageNamed:kDefaultImage];
[imageView setImage:defaultImage];
cell.accessoryView = imageView;
[imageView release];
}
cell.textLabel.text = reminderDetailsString;
return cell;
}
Can any one please help me,thanks in advance :)
just set dequeueReusableCellWithIdentifier to nil and also reuseIdentifier to nil like bellow..
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:nil];
and
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil] autorelease];
and also add your other code in this if (cell == nil) if condition..
UPDATE:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
NSString *CellIdentifier = [NSString stringWithFormat:#"Cell%d%d",indexPath.section,indexPath.row];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
cell.textLabel.numberOfLines = 0;
cell.textLabel.font = [UIFont fontWithName:kHelvetica size:17.0];
cell.textLabel.adjustsFontSizeToFitWidth = YES;
cell.backgroundColor = [UIColor clearColor];
tableView.backgroundColor = [UIColor clearColor];
NSDateFormatter *dateFormat = [[[NSDateFormatter alloc]init]autorelease];
[dateFormat setDateFormat:kDateFormat];
NSDate *reminderDate = [dateFormat dateFromString:reminderToDisplay.Date];
[dateFormat setDateFormat:kMinDateFormat];
NSString *dateString = [dateFormat stringFromDate:reminderDate];
NSString *valueString = [NSString stringWithFormat:kNameEvent,reminderToDisplay.Name,reminderToDisplay.Event];
NSString *onString = [NSString stringWithFormat:kOn,dateString];
NSString *reminderDetailsString = [valueString stringByAppendingString:onString];
ABAddressBookRef addressbook = ABAddressBookCreate();
CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressbook);
CFIndex numPeople = ABAddressBookGetPersonCount(addressbook);
for (int i=0; i < numPeople; i++)
{
ABRecordRef person = CFArrayGetValueAtIndex(allPeople, i);
NSString *firstName=(NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty);
NSString *lastName=(NSString *)ABRecordCopyValue(person, kABPersonLastNameProperty);
NSMutableDictionary *contactsDictionary = [[[NSMutableDictionary alloc]init]autorelease];
if(firstName != nil && firstName != NULL)
{
[contactsDictionary setObject:firstName forKey:kFirstName];
CFRelease(firstName);
}
else
{
[contactsDictionary setObject:#"" forKey:kFirstName];
}
if(lastName != nil && lastName != NULL)
{
[contactsDictionary setObject:lastName forKey:kLastName];
CFRelease(lastName);
}
else
{
[contactsDictionary setObject:#"" forKey:kLastName];
}
//Get the first name and last name added to dict and combine it to form contact name
firstName = [[[NSString alloc]initWithString:[contactsDictionary objectForKey:kFirstName]]autorelease];
lastName = [NSString stringWithFormat:#" %#",[contactsDictionary objectForKey:kLastName]];
self.contactName = [firstName stringByAppendingString:lastName];
//Now check whether the contact name is same as your reminderToDisplay.Name
if([reminderToDisplay.Name isEqualToString:contactName] && ABPersonHasImageData(person))
{
CFDataRef imageData = ABPersonCopyImageData(person);
self.reminderImage = [UIImage imageWithData:(NSData *)imageData];
CFRelease(imageData);
}
}
CFRelease(allPeople);
CFRelease(addressbook);
if ([reminderToDisplay.reminderGroup isEqualToString:kFacebook])
{
NSString *imageName = [NSString stringWithFormat:kImageName,reminderToDisplay.Name];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *reminderString=[documentsDirectory stringByAppendingPathComponent:[NSString stringWithString:imageName]];
self.reminderImage = [UIImage imageWithContentsOfFile:reminderString];
}
if (reminderImage != nil)
{
UIImageView *imageView=[[UIImageView alloc] initWithFrame:CGRectMake(240, 3, 70, 63)];
imageView.backgroundColor=[UIColor clearColor];
[imageView setImage:reminderImage];
cell.accessoryView = imageView;
[imageView release];
}
else
{
UIImageView *imageView=[[UIImageView alloc] initWithFrame:CGRectMake(240, 3, 70, 63)];
imageView.backgroundColor=[UIColor clearColor];
UIImage *defaultImage = [UIImage imageNamed:kDefaultImage];
[imageView setImage:defaultImage];
cell.accessoryView = imageView;
[imageView release];
}
cell.textLabel.text = reminderDetailsString;
}
return cell;
}

IPhone UITableView jerky when scrolling

I'm loading my table from an XML feed in to an array then creating the cells as the code below shows. It can be really jerky when loading sometimes. I thought that was just the images downloading when I scroll but I removed them to test and sometimes it was still jerky. Can't work out what I'm doing wrong!
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
const NSInteger BOTTOM_LABEL_TAG = 1002;
const NSInteger TEXT_FIELD_TAG = 1003;
UILabel *Labelcompanyname;
UILabel *Labeldistance;
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell =
[[[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier]
autorelease];
const CGFloat LABEL_HEIGHT = 15;
int spaceSize;
if(currentType == #"categorySearch"){
spaceSize = 57;
}
else {
spaceSize = 34;
}
Labelcompanyname =
[[[UILabel alloc]
initWithFrame:
CGRectMake(
spaceSize + 2.0 * cell.indentationWidth,
0.5 * (tableView.rowHeight - 2 * LABEL_HEIGHT)+10,
tableView.bounds.size.width -
spaceSize - 20.0,
LABEL_HEIGHT)]
autorelease];
[cell.contentView addSubview:Labelcompanyname];
Labeldistance =[[[UILabel alloc]
initWithFrame:
CGRectMake(
spaceSize + 2.0 * cell.indentationWidth,
0.5 * (tableView.rowHeight - 2 * LABEL_HEIGHT)+40,
tableView.bounds.size.width -
spaceSize - 20.0,
LABEL_HEIGHT)]
autorelease];
if(currentType == #"categorySearch") {
[cell.contentView addSubview:Labeldistance];
}
Labelcompanyname.tag = BOTTOM_LABEL_TAG;
Labelcompanyname.font = [UIFont systemFontOfSize:[UIFont labelFontSize] - 2];
Labeldistance.tag = TEXT_FIELD_TAG;
Labeldistance.font = [UIFont systemFontOfSize:[UIFont labelFontSize] - 2];
cell.backgroundView = [[[UIImageView alloc] init] autorelease];
cell.selectedBackgroundView = [[[UIImageView alloc] init] autorelease];
cell.textLabel.numberOfLines=0;
}
else
{
Labelcompanyname = (UILabel *)[cell viewWithTag:BOTTOM_LABEL_TAG];
Labeldistance = (UILabel *)[cell viewWithTag:TEXT_FIELD_TAG];
}
PromotionObject *newObj1;
newObj1=[totalArray objectAtIndex:indexPath.row];
if(!newObj1.furtherURL){
Labelcompanyname.text =[NSString stringWithFormat:#"%#", newObj1.companyname];
Labeldistance.text =newObj1.distance;
}
else
{
Labelcompanyname.text =[NSString stringWithFormat:#"Load more results"];
Labeldistance.text =#"";
}
NSURL *Imageurl = [NSURL URLWithString:[NSString stringWithFormat:#"%#", newObj1.locImage]];
NSData *data = [NSData dataWithContentsOfURL:Imageurl];
UIImage *img = [[[UIImage alloc] initWithData:data] autorelease];
if(currentType == #"categorySearch"){
cell.imageView.image = img;
} else if(currentType == #"fullSearch") {
cell.imageView.image = [UIImage imageNamed:#"newmap.png"];
} else {
cell.imageView.image = [UIImage imageNamed:#"business.png"];
}
cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
Any help will be really appreciated
Tom
You definitely shouldn't do anything that blocks the UI thread for significant time while loading cells. E.g. NSData *data = [NSData dataWithContentsOfURL:Imageurl];.
I recommend loading your images into the data source in the background and reload/update the table/cells when the data has been downloaded. Would also be good to implement a cache for your images so you don't have to download them again everytime the cell is loaded.
If you need help with asynchronous image loading, search for that. Lot's of stuff on SO.
I guess you got your answer yourself. Your image loading blocks your UI from finishing the current cell request. tableView:cellForRowAtIndexPath: can't return until your image is fetched. I suggest you replace your image by an activity indicator and start to fetch your image in background. You might want to take a look at Concurrency Programming Guide

UITableView Accessory View not being displayed

Why is the following not displaying the proper UITableView accessory view? It is simply displaying the UIAcessoryTypeCheckmark that was selected in the nib file.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForManagedObject:(NSManagedObject *)managedObject withIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = #"Selection";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil) {
cell = tvCell;
self.tvCell = nil;
}
self.tableView.rowHeight = 70.0f;
//Background
BOOL useDarkBackground = NO; //odd
if(indexPath.row %2 == 0) useDarkBackground = YES; //even
NSString *backgroundImagePath = [[NSBundle mainBundle] pathForResource:useDarkBackground ? #"DarkBackground" : #"LightBackground" ofType:#"png"];
UIImage *backgroundImage = [[UIImage imageWithContentsOfFile:backgroundImagePath] stretchableImageWithLeftCapWidth:0.0 topCapHeight:1.0];
cell.backgroundView = [[[UIImageView alloc] initWithImage:backgroundImage] autorelease];
cell.backgroundView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
cell.backgroundView.frame = cell.bounds;
//Checkmark
cell.userInteractionEnabled = YES;
NSString *checkmarkImagePath;
checkmarkImagePath = [[NSBundle mainBundle] pathForResource:[selectedObjects containsObject:managedObject] ? #"checkSelected" : #"checkUnselected" ofType:#"png"];
if([selectedObjects count] == 0) {
checkmarkImagePath = [[NSBundle mainBundle] pathForResource:#"checkUnselected" ofType:#"png"];
}
UIImage *checkmarkImage = [[UIImage imageWithContentsOfFile:checkmarkImagePath] stretchableImageWithLeftCapWidth:0.0 topCapHeight:1.0];
UIImageView *imageView = [[[UIImageView alloc] initWithImage:checkmarkImage] autorelease];
imageView.contentMode = UIViewContentModeScaleAspectFit;
imageView.frame = CGRectMake(10.0, 10.0, imageView.frame.size.width/1.2, imageView.frame.size.height/1.2);
return cell;
}
For some reason, the following does work:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSManagedObject *objectToChange = [[self fetchedResultsControllerForTableView:tableView] objectAtIndexPath:indexPath]; //The object
[tableView deselectRowAtIndexPath:[tableView indexPathForSelectedRow] animated:NO];
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
NSString *checkmarkImagePath = [[NSBundle mainBundle] pathForResource:[selectedObjects containsObject:objectToChange] ? #"checkSelected" : #"checkUnselected" ofType:#"png"];
UIImage *checkmarkImage = [[UIImage imageWithContentsOfFile:checkmarkImagePath] stretchableImageWithLeftCapWidth:0.0 topCapHeight:1.0];
UIImageView *imageView = [[[UIImageView alloc] initWithImage:checkmarkImage] autorelease];
imageView.contentMode = UIViewContentModeScaleAspectFit;
imageView.frame = CGRectMake(10.0, 10.0, imageView.frame.size.width/1.2, imageView.frame.size.height/1.2);
cell.accessoryView = imageView;
}
Thanks a lot!
It doesn't look like you're adding the UIImageView to the accessory view of the cell in the first code block.
You're also leaking all over the place. Make sure you adhere to the memory management guidelines set forth by Apple.
In your cellForRowAtIndexPath, you are not assigning the accessoryView to the cell, as you are in the didSelect method.

Objective-C: First item of NSArray sometimes is missing

I have and NSArray with 5 string elements, populating an UITableView of my iPhone App.
Everything works fine, but sometimes the first string of my array is missing and I can't figure out why.
Here is my code:
arrayList = [[NSArray alloc] initWithObjects: #"My First String",
#"My Second String",
#"My Third String",
#"My Forth String",
#"My Fifth Sring",
nil];
The element that sometimes just doesn't show up is My First String
Actually I'm using this sample code from Cocoa With Love. Thanks guys for helping me!
- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
#if USE_CUSTOM_DRAWING
const NSInteger TOP_LABEL_TAG = 1001;
// const NSInteger BOTTOM_LABEL_TAG = 1002;
UILabel *topLabel;
// UILabel *bottomLabel;
#endif
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [aTableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
//
// Create the cell.
//
cell =
[[[UITableViewCell alloc]
initWithFrame:CGRectZero
reuseIdentifier:CellIdentifier]
autorelease];
#if USE_CUSTOM_DRAWING
UIImage *indicatorImage = [UIImage imageNamed:#"image1.png"];
cell.accessoryView =
[[[UIImageView alloc]
initWithImage:indicatorImage]
autorelease];
const CGFloat LABEL_HEIGHT = 22;
UIImage *image = [UIImage imageNamed:#"image2.png"];
//
// Create the label for the top row of text
//
topLabel =
[[[UILabel alloc]
initWithFrame:
CGRectMake(
image.size.width + 2.0 * cell.indentationWidth,
0.5 * (aTableView.rowHeight - 1.3 * LABEL_HEIGHT),
aTableView.bounds.size.width -
image.size.width - 4.0 * cell.indentationWidth
- indicatorImage.size.width,
LABEL_HEIGHT)]
autorelease];
[cell.contentView addSubview:topLabel];
//
// Configure the properties for the text that are the same on every row
//
topLabel.tag = TOP_LABEL_TAG;
topLabel.backgroundColor = [UIColor clearColor];
topLabel.textColor = [UIColor colorWithRed:0.25 green:0.0 blue:0.0 alpha:1.0];
topLabel.highlightedTextColor = [UIColor colorWithRed:1.0 green:1.0 blue:0.9 alpha:1.0];
topLabel.font = [UIFont systemFontOfSize:[UIFont labelFontSize]];
topLabel.textAlignment = UITextAlignmentCenter;
/*
//
// Create the label for the bottom row of text
//
bottomLabel =
[[[UILabel alloc]
initWithFrame:
CGRectMake(
image.size.width + 2.0 * cell.indentationWidth,
0.5 * (aTableView.rowHeight - 2 * LABEL_HEIGHT) + LABEL_HEIGHT,
aTableView.bounds.size.width -
image.size.width - 4.0 * cell.indentationWidth
- indicatorImage.size.width,
LABEL_HEIGHT)]
autorelease];
[cell.contentView addSubview:bottomLabel];
//
// Configure the properties for the text that are the same on every row
//
bottomLabel.tag = BOTTOM_LABEL_TAG;
bottomLabel.backgroundColor = [UIColor clearColor];
bottomLabel.textColor = [UIColor colorWithRed:0.25 green:0.0 blue:0.0 alpha:1.0];
bottomLabel.highlightedTextColor = [UIColor colorWithRed:1.0 green:1.0 blue:0.9 alpha:1.0];
bottomLabel.font = [UIFont systemFontOfSize:[UIFont labelFontSize] - 2];
*/
//
// Create a background image view.
//
cell.backgroundView =
[[[UIImageView alloc] init] autorelease];
cell.selectedBackgroundView =
[[[UIImageView alloc] init] autorelease];
#endif
}
#if USE_CUSTOM_DRAWING
else
{
topLabel = (UILabel *)[cell viewWithTag:TOP_LABEL_TAG];
// bottomLabel = (UILabel *)[cell viewWithTag:BOTTOM_LABEL_TAG];
}
topLabel.text = [arrayList objectAtIndex:indexPath.row];
//bottomLabel.text = [NSString stringWithFormat:#"Some other information.", [indexPath row]];
// [cell LabelText:[arrayList objectAtIndex:indexPath.row]];
//
// Set the background and selected background images for the text.
// Since we will round the corners at the top and bottom of sections, we
// need to conditionally choose the images based on the row index and the
// number of rows in the section.
//
UIImage *rowBackground;
UIImage *selectionBackground;
NSInteger sectionRows = [aTableView numberOfRowsInSection:[indexPath section]];
NSInteger row = [indexPath row];
if (row == 0 && row == sectionRows - 1)
{
rowBackground = [UIImage imageNamed:#"topAndBottomRow.png"];
selectionBackground = [UIImage imageNamed:#"topAndBottomRowSelected_copy.png"];
}
else if (row == 0)
{
rowBackground = [UIImage imageNamed:#"topRow.png"];
selectionBackground = [UIImage imageNamed:#"topRowSelected_copy.png"];
}
else if (row == sectionRows - 1)
{
rowBackground = [UIImage imageNamed:#"bottomRow.png"];
selectionBackground = [UIImage imageNamed:#"bottomRowSelected_copy.png"];
}
else
{
rowBackground = [UIImage imageNamed:#"middleRow.png"];
selectionBackground = [UIImage imageNamed:#"middleRowSelected_copy.png"];
}
((UIImageView *)cell.backgroundView).image = rowBackground;
((UIImageView *)cell.selectedBackgroundView).image = selectionBackground;
if (row == 0)
{
cell.imageView.image = [UIImage imageNamed:#"pic1.png"];
}
else if (row == 1)
{
cell.imageView.image = [UIImage imageNamed:#"pic2.png"];
}
else if (row == 2)
{
cell.imageView.image = [UIImage imageNamed:#"pic3.png"];
}
else if (row == 3)
{
cell.imageView.image = [UIImage imageNamed:#"pic4.png"];
}
else if (row == 4)
{
cell.imageView.image= [UIImage imageNamed:#"pic5.png"];
}
#else
[cell LabelText:[arrayList objectAtIndex:indexPath.row]];
//cell.text = [NSString stringWithFormat:#"Cell at row %ld.", [indexPath row]];
#endif
return cell;
}
The issue you are probably having is accessing object 1 as index 1... Arrays in Objective-C are the same as most other C structured languages. Indexed starting at 0.
Put this code in.
for (int i = 0; i < [arrayList count]; i++)
{
NSLog(#"Item %d = %#", i, [arrayList objectAtIndex:i]);
}
Chances are good that this works fine.
If that is not the case the I would recommend restoring your iphone to factory default as either the operating system is malfunctioning, or you have other rogue processes that are corrupting memory.
To debug the code above. As you are grabbing the items out of the array I would put in an NSLog()
NSString *objectAtIndex = [arrayList objectAtIndex:indexPath.row];
NSLog(#"Row: %d, Object: %#, Count: %d",indexPath.row, objectAtIndex, [arrayList count]);
[cell LabelText:[arrayList objectAtIndex:indexPath.row]];
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
cell.textLabel.text = [arrayList objectAtIndex:indexPath.row];
return cell;
}
Are you doing something similar to this for populating table view
NSMutableArray *ArrayList=[[NSMutableArray alloc]initWithObjects: #"My First String",
#"My Second String",
#"My Third String",
#"My Forth String",
#"My Fifth Sring",
nil];

UITableViewCell loading issues

i have a UITableViewCell loading 10 images its loads the first 6, then its saying (cell != nil) so it doesnt load the remaining images, but if i remove the "if(cell==nil)" it loads all the images
am i missing something?
thanks
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
AsyncImageView *asyncImageView = nil;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
int section = indexPath.section;
NSMutableArray *sectionItems = [sections objectAtIndex:section];
if (cell == nil) {
NSLog(#"CELL == NIL %#", cell);
int n = ([sectionItems count]) ;
cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
cell.accessoryType = UITableViewCellAccessoryNone;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
int i=0,f=0;
while (i < n)
{
int yy = 4 +f*74;
for(int j=0; j<3;j++){
Item *item = [sectionItems objectAtIndex:i];
int buttonX = 10;
if (i == 0) {
buttonX = 10;
}else {
buttonX = 203
}
CGRect frame;
frame.origin.x = buttonX;
frame.origin.y = yy;
frame.size.width = 107;
frame.size.height = 107;
asyncImageView = [[[AsyncImageView alloc] initWithFrame:frame] autorelease];
asyncImageView.tag = ASYNC_IMAGE_TAG;
NSString *urlString = item.image;
NSURL *url = [NSURL URLWithString:urlString];
[asyncImageView loadImageFromURL:url];
[cell.contentView addSubview:asyncImageView];
i++;
}
f = f+1;
}
}
else {
NSLog(#"cell != nill");
asyncImageView = (AsyncImageView *) [cell.contentView viewWithTag:ASYNC_IMAGE_TAG];
}
return cell;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
NSLog(#"CELL == NIL %#", cell);
cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
cell.accessoryType = UITableViewCellAccessoryNone;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
CGRect frame = CGRectMake(0,20,30,40);
UIImageView *img = [[[UIImageView alloc] initWithFrame:frame];
img.tag = IMAGE_TAG;
[cell.contentView addSubview:img];
[img release];
}int row = indexPath.row;
UIImageView *myImage = = (UIImageView *) [cell.contentView viewWithTag:IMAGE_TAG];
UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:#"%d" , row]];
[myImage setImage:image];
return cell;}
UITableViewCells are cached to save memory and allocations costs (hence performance). You only create a cell once and after that you set it contents based on your index path. I've simply created an imageview in the cell and later on set an image depending on the indexpath in that cell (1.png , 2.png etc).
Read the documentation here.
UITableViewCells are re-used to save time and memory, typically, and you're using this paradigm I see. You need to implement the cell != nil case and set up the cell to display the contents based on the indexPath. The cell was previously used to display other content so you need to adjust all indexPath-dependent views in the non-nil cell.