Objective-C: First item of NSArray sometimes is missing - iphone

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];

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;
}

Can anyone tell me why tableview data are not displaying until scroll?

In my tableview i have set xml data to display but until scroll it does not display all value. I have reloaded the tableview when i am getting my xml data. I also used [cell.contenView viewWithTag:tagnumber]; But still now its not Working...please help me anybody....
Data are coming and using NSLog i can get the value but not display until scroll.
One think i have to mention that i can see the my cellview and imageview but not showing lable data.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *MyIdentifier = #"MyIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil) {
//cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease];
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier] autorelease];
cell.textLabel.font = [UIFont fontWithName:#"Helvetica" size:15.0];
cell.selectionStyle = UITableViewCellSelectionStyleBlue;
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"arrow.png"]];
cell.accessoryView = imageView;
tableView.separatorColor = [UIColor clearColor];
tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
// THIS IS A VIEW ABOVE MY CELL NAME: cellView
cellView = [[[UIView alloc] initWithFrame:CGRectMake(0,0,290, 120)] autorelease];
cellView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"order_description_bg.png"]];
cellView.tag =10;
// THIS IS A IMAGEVIEW ABOVE MY cellView NAME: imgView
imgView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 15, 39, 36)];
imgView.image = [UIImage imageNamed:#"order_image.png"];
imgView.layer.borderColor = [UIColor blackColor].CGColor;
imgView.layer.borderWidth = 0.0f;
imgView.tag = 5;
// THIS IS A LABEL ABOVE MY cellView NAME: statusLabel
CGRect statusRect = CGRectMake(65, 0, 190, 18);
statusLabel = [[[UILabel alloc] initWithFrame:statusRect] autorelease];
statusLabel.textAlignment = UITextAlignmentLeft;
statusLabel.textColor = [UIColor blackColor];
statusLabel.font = [UIFont systemFontOfSize:12];
statusLabel.backgroundColor = [UIColor greenColor];
statusLabel.tag = 1;
[cell.contentView addSubview:cellView];
[cellView addSubview:statusLabel];
[cellView addSubview:imgView];
}
// [cell.contentView superview];
cellView = (UIView *)[cell.contentView viewWithTag:10];
imgView = (UIImageView *)[cellView viewWithTag:5];
statusLabel = (UILabel *)[cellView viewWithTag:1];
if(searching == YES && x<=inumOfRowAfterSearch){
NSLog(#"[[searchData objectAtIndex:m] intValue] is : %d",[[searchData objectAtIndex:inumOfRowAfterSearch] intValue]);
y = [[searchData objectAtIndex:inumOfRowAfterSearch] intValue];
cellView = (UIView *)[cell.contentView viewWithTag:10];
imgView = (UIImageView *)[cellView viewWithTag:5];
statusLabel = (UILabel *)[cellView viewWithTag:1];
if(pendingOrder == NO && todaysOrder == NO && x<=inumOfRowAfterSearch){
statusLabel.text = [NSString stringWithFormat:#"Status: %#",[[records objectAtIndex:y] objectAtIndex:1]];
}
else if(pendingOrder == YES && todaysOrder == NO && x<=inumOfRowAfterSearch){
statusLabel.text = [NSString stringWithFormat:#"Status: %#",[[records objectAtIndex:y] objectAtIndex:1]];
}
}
else{
cellView = (UIView *)[cell.contentView viewWithTag:10];
imgView = (UIImageView *)[cellView viewWithTag:5];
statusLabel = (UILabel *)[cellView viewWithTag:1];
if(pendingOrder == NO && todaysOrder == NO){
statusLabel.text = [NSString stringWithFormat:#"Status: %#",[[records objectAtIndex:indexPath.section] objectAtIndex:1]];
NSLog(#"status lable value: %#",statusLabel.text);
}
else if(pendingOrder == YES && todaysOrder == NO){
statusLabel.text = [NSString stringWithFormat:#"Status: %#",[[pendingRecords objectAtIndex:indexPath.section] objectAtIndex:1]];
}
}
return cell;
}
Before scroll the table.
After Scroll the tableview
Following codes are not necessary in each condition , since you have written the code outside of the condition. It seems duplicate.
cellView = (UIView *)[cell.contentView viewWithTag:10];
imgView = (UIImageView *)[cellView viewWithTag:5];
statusLabel = (UILabel *)[cellView viewWithTag:1];
And coming to your question, it seems initially it skips both if and else if conditions. Comment also the NSLogs and write NSLog in else part of the conditions.
Edit:
// [cell.contentView superview];
cellView = (UIView *)[cell.contentView viewWithTag:10];
imgView = (UIImageView *)[cellView viewWithTag:5];
statusLabel = (UILabel *)[cellView viewWithTag:1];
if(searching == YES && x<=inumOfRowAfterSearch){
NSLog(#"[[searchData objectAtIndex:m] intValue] is : %d",[[searchData objectAtIndex:inumOfRowAfterSearch] intValue]);
y = [[searchData objectAtIndex:inumOfRowAfterSearch] intValue];
if(pendingOrder == NO && todaysOrder == NO ){
statusLabel.text = [NSString stringWithFormat:#"Status: %#",[[records objectAtIndex:y] objectAtIndex:1]];
}
else if(pendingOrder == YES && todaysOrder == NO ){
statusLabel.text = [NSString stringWithFormat:#"Status: %#",[[records objectAtIndex:y] objectAtIndex:1]];
}
else
{
statusLabel.text = [NSString stringWithFormat:#"Status: None"];
}
}
else{
if(pendingOrder == NO && todaysOrder == NO){
statusLabel.text = [NSString stringWithFormat:#"Status: %#",[[records objectAtIndex:indexPath.section] objectAtIndex:1]];
NSLog(#"status lable value: %#",statusLabel.text);
}
else if(pendingOrder == YES && todaysOrder == NO){
statusLabel.text = [NSString stringWithFormat:#"Status: %#",[[pendingRecords objectAtIndex:indexPath.section] objectAtIndex:1]];
}
else
{
statusLabel.text = [NSString stringWithFormat:#"Status: None"];
}
}
return cell;

tableview refreshing while searching on iphone

I have a table view that shows 3 data side by side in table ,lets say A(name) , B(roll no) , C(id).
Now if user do search based on A's (search by name) (table get refreshed with name while searching only) value I want to either hide the content of B & C or they should show the correct value while search is on , not the old value which they got before searching.
I couldn't find the solution how to deal with remaining B & C.kindly suggest
here is my code
- (void) searchTableView
{
NSLog(#"search button is down %#",searchBar.text);
NSString *searchText = searchBar.text;
NSMutableArray *searchArray = [[NSMutableArray alloc] init];
if(SearchQuery==1)
{
[searchArray addObjectsFromArray:[entityArray valueForKey:#"Name"]];
}
if(SearchQuery==2)
{
[searchArray addObjectsFromArray:[entityArray valueForKey:#"IC"]];
}
for (NSString *sTemp in searchArray)
{
NSLog(#"copyListOfItems in search -%#",copyListOfItems);//final array for names
NSRange titleResultsRange = [sTemp rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (titleResultsRange.length > 0)
[copyListOfItems addObject:sTemp];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSManagedObject *object = (NSManagedObject *)[entityArray objectAtIndex:indexPath.row];
NSString *CellIdentifier = #"Cell";
int indicator = UITableViewCellAccessoryNone;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
mainLabel = [[[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 50.0)] autorelease];//220
mainLabel.tag = MAINLABEL_TAG;
[mainLabel setFont:[UIFont fontWithName:#"Helvetica-Bold" size:18]];//Palatino-BoldItalic
mainLabel.textAlignment = UITextAlignmentLeft;
mainLabel.textColor = [UIColor blackColor];
secondLabel = [[[UILabel alloc] initWithFrame:CGRectMake(313.0, 9.0, 200.0, 25.0)] autorelease];//83
secondLabel.tag = SECONDLABEL_TAG;
smallSystemFontSize]]];
[secondLabel setFont:[UIFont fontWithName:#"Helvetica" size:18]];
secondLabel.textAlignment = UITextAlignmentLeft;
secondLabel.textColor = [UIColor blackColor];
[cell.contentView addSubview:secondLabel];
//// 3rd labl display
thirdLabel = [[[UILabel alloc] initWithFrame:CGRectMake(560.0, 9.0, 250.0, 25.0)] autorelease];//83
thirdLabel.tag = THIRDLABEL_TAG;
//thirdLabel.font = [UIFont systemFontOfSize:13.0];
[thirdLabel setFont:[UIFont fontWithName:#"Helvetica" size:18]];//Palatino-BoldItalic
thirdLabel.textAlignment = UITextAlignmentLeft;
thirdLabel.textColor = [UIColor blackColor];
[cell.contentView addSubview:thirdLabel];
}
if(searching)
{
NSLog(#" seacrh List in table view =%#",[copyListOfItems objectAtIndex:indexPath.row]);
// NSString *s=[object valueForKey:#"Name"];
NSLog(#"copyListOfItems length ---------%d",[copyListOfItems count]);
cell.textLabel.text =[copyListOfItems objectAtIndex:indexPath.row] ;
if(SearchQuery==2)
{
secondLabel.text=#"kk";// not working
secondLabel.alpha=1; // this is not working i cant upadate
}
}
else
{
if(self.entityName == #"Parent")
{
{
indicator = UITableViewCellAccessoryDisclosureIndicator;
CellIdentifier = #"CellWithDisclosure";
}
}
if(SearchQuery==2)
{
cell.textLabel.text =[object valueForKey:#"IC"] ;
secondLabel = (UILabel *)[cell.contentView viewWithTag:SECONDLABEL_TAG];
thirdLabel = (UILabel *)[cell.contentView viewWithTag:THIRDLABEL_TAG];
NSLog(#"sex is %# ",[object valueForKey:#"Name"]);
secondLabel.text=[object valueForKey:#"Name"] ;
secondLabel.alpha=0;
thirdLabel.text=[object valueForKey:#"roll"] ;
}

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

How can I search data from tableview cell?

I have an UITableview controller which representing fetched XML data. For representing these data I used five UILabel. Now I have to add a searchbar at the top of the UITableview. So programmatically I have added a searchbar.
Now I have used searching theorem for search data from the UITableview. But It is not working. I can search data from UItableview when only one text in the UItableviewcell without any UIlabel or something else but in my UItableviewcell cell are taking five UILabel that's why it's becoming tough for me to search data from the UItableviewcell. For understanding I am attaching my code how I am representing my XML data in tableview cell.
This is my XML data representation in UITableviewCell...
static NSString *MyIdentifier = #"MyIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease];
cell.textLabel.font = [UIFont fontWithName:#"Helvetica" size:15.0];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"arrow.png"]];
cell.accessoryView = imageView;
cell.accessoryType = UITableViewCellSelectionStyleNone;
tableView.separatorColor = [UIColor clearColor];
tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
cellView = [[[UIView alloc] initWithFrame:CGRectMake(5,8,290, 120)] autorelease];
cellView.backgroundColor = [UIColor clearColor];
cellView.tag =10;
[cell.contentView addSubview:cellView];
imgView = [[UIImageView alloc] initWithFrame:CGRectMake(2, 40, 48, 48)];
imgView.image = [UIImage imageNamed:#"productbox.png"];
imgView.layer.borderColor = [UIColor blackColor].CGColor;
imgView.layer.borderWidth = 2.0;
imgView.tag = 5;
[cellView addSubview:imgView];
CGRect idLabelRect = CGRectMake(65, 0, 190, 18);
idLabel = [[[UILabel alloc] initWithFrame:idLabelRect] autorelease];
idLabel.textAlignment = UITextAlignmentLeft;
idLabel.textColor = [UIColor blackColor];
idLabel.font = [UIFont systemFontOfSize:12];
idLabel.backgroundColor = [UIColor clearColor];
idLabel.layer.borderColor = [UIColor grayColor].CGColor;
idLabel.tag = 0;
CGRect statusRect = CGRectMake(65, 22, 190, 22);
statusLabel = [[[UILabel alloc] initWithFrame:statusRect] autorelease];
statusLabel.textAlignment = UITextAlignmentLeft;
statusLabel.textColor = [UIColor blackColor];
statusLabel.font = [UIFont systemFontOfSize:12];
statusLabel.backgroundColor = [UIColor clearColor];
statusLabel.layer.borderColor = [UIColor grayColor].CGColor;
statusLabel.tag = 1;
CGRect orderDateRect = CGRectMake(65, 48, 190, 22);
orderDate = [[[UILabel alloc] initWithFrame:orderDateRect] autorelease];
orderDate.textAlignment = UITextAlignmentLeft;
orderDate.textColor = [UIColor blackColor];
orderDate.font = [UIFont systemFontOfSize:12];
orderDate.backgroundColor = [UIColor clearColor];
orderDate.layer.borderColor = [UIColor grayColor].CGColor;
orderDate.tag = 2;
CGRect byRect = CGRectMake(65, 75, 190, 22);
byLabel = [[[UILabel alloc] initWithFrame:byRect] autorelease];
byLabel.textAlignment = UITextAlignmentLeft;
byLabel.textColor = [UIColor blackColor];
byLabel.font = [UIFont systemFontOfSize:12];
byLabel.backgroundColor = [UIColor clearColor];
byLabel.layer.borderColor = [UIColor grayColor].CGColor;
byLabel.tag = 3;
CGRect totalRect = CGRectMake(65, 98, 190, 22);
totalLabel = [[[UILabel alloc] initWithFrame:totalRect] autorelease];
totalLabel.textAlignment = UITextAlignmentLeft;
totalLabel.textColor = [UIColor blackColor];
totalLabel.font = [UIFont systemFontOfSize:12];
totalLabel.backgroundColor = [UIColor clearColor];
totalLabel.layer.borderColor = [UIColor grayColor].CGColor;
totalLabel.tag = 4;
[cellView addSubview:idLabel];
[cellView addSubview:statusLabel];
[cellView addSubview:orderDate];
[cellView addSubview:byLabel];
[cellView addSubview:totalLabel];
}
if(searching == YES){
//[cell setText:[tableData objectAtIndex:indexPath.row]];
cell.textLabel.text = [tableData objectAtIndex:indexPath.row];
}
else{
cellView = (UIView *)[cell.contentView viewWithTag:10];
idLabel = (UILabel *)[cellView viewWithTag:0];
statusLabel = (UILabel *)[cellView viewWithTag:1];
orderDate = (UILabel *)[cellView viewWithTag:2];
byLabel = (UILabel *)[cellView viewWithTag:3];
totalLabel = (UILabel *)[cellView viewWithTag:4];
imgView = (UIImageView *)[cellView viewWithTag:5];
if(pendingOrder == NO && todaysOrder == NO){
idLabel.text = [NSString stringWithFormat:#"Order Id: %#",[[records objectAtIndex:indexPath.section] objectAtIndex:0]];
statusLabel.text = [NSString stringWithFormat:#"Status: %#",[[records objectAtIndex:indexPath.section] objectAtIndex:1]];
orderDate.text = [NSString stringWithFormat:#"Date: %#",[[records objectAtIndex:indexPath.section] objectAtIndex:2]];
byLabel.text =[NSString stringWithFormat:#"By: %#",[[records objectAtIndex:indexPath.section] objectAtIndex:3]];
totalLabel.text =[NSString stringWithFormat:#"Total: %#",[[records objectAtIndex:indexPath.section] objectAtIndex:4]];
}
else if(pendingOrder == YES && todaysOrder == NO){
idLabel.text = [NSString stringWithFormat:#"Order Id: %#",[[pendingRecords objectAtIndex:indexPath.section] objectAtIndex:0]];
statusLabel.text = [NSString stringWithFormat:#"Status: %#",[[pendingRecords objectAtIndex:indexPath.section] objectAtIndex:1]];
orderDate.text = [NSString stringWithFormat:#"Date: %#",[[pendingRecords objectAtIndex:indexPath.section] objectAtIndex:2]];
byLabel.text =[NSString stringWithFormat:#"By: %#",[[pendingRecords objectAtIndex:indexPath.section] objectAtIndex:3]];
totalLabel.text =[NSString stringWithFormat:#"Total: %#",[[pendingRecords objectAtIndex:indexPath.section] objectAtIndex:4]];
}
}
return cell;
}
And this searching Delegate.....
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
searching = YES;
// only show the status bar’s cancel button while in edit mode
sBar.showsCancelButton = YES;
sBar.autocorrectionType = UITextAutocorrectionTypeNo;
// flush the previous search content
[tableData removeAllObjects];
}
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar{
searching = NO;
sBar.showsCancelButton = NO;
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
[tableData removeAllObjects];// remove all data that belongs to previous search
if([searchText isEqualToString:#""] && searchText==nil){
[tableview reloadData];
return;
}
NSInteger counter = 0;
for(NSString *name in dataSource)
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
NSRange r = [name rangeOfString:searchText];
if(r.location != NSNotFound)
{
if(r.location== 0)//that is we are checking only the start of the names.
{
[tableData addObject:name];
}
}
counter++;
[pool release];
}
[tableview reloadData];
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
// if a valid search was entered but the user wanted to cancel, bring back the main list content
[tableData removeAllObjects];
searching = NO;
[tableData addObjectsFromArray:dataSource];
#try{
searching = NO;
[tableview reloadData];
}
#catch(NSException *e){
}
[sBar resignFirstResponder];
sBar.text = #"";
}
// called when Search (in our case “Done”) button pressed
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
[sBar resignFirstResponder];
}
For more help to understand i am also attaching my viewDidLoad....
//Add the search bar
sBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0,0,320,50)];
sBar.delegate = self;
searching = NO;
[self.view addSubview:sBar];
tableview.dataSource = self;
tableview.delegate = self;
//initialize the two arrays; datasource will be initialized and populated by appDelegate
searchData = [[NSMutableArray alloc] init];
tableData = [[NSMutableArray alloc] init];
[tableData addObjectsFromArray:dataSource];//on launch it should display all the records
Edit
This is my edited portion of numberOfSectionsInTableView and numberOfRowsInSection...
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
if(searching == YES){
searching = NO;
sectionCount = [tableData count];
}
else {
if(pendingOrder == NO && todaysOrder == NO){
sectionCount = [records count];
NSLog(#"section cout: %d",sectionCount);
}
else if(pendingOrder == YES && todaysOrder == NO){
//Total pending order counting
sectionCount = [pendingRecords count];
NSLog(#"section cout for pending: %d",sectionCount);
}
else if(pendingOrder == NO && todaysOrder == YES){
NSLog(#"todays order number counting");
}
}
return sectionCount;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 1;
}
Try this:-
copylistofItem is NSMutableArray copying data that matched with search bar criteria.
- (void) searchBarSearchButtonClicked:(UISearchBar *)theSearchBar {
NSString *searchText = searchBar.text;
NSMutableArray *searchArray = [[NSMutableArray alloc] init];
int i=0
for (NSString *str in [records objectAtIndex:indexPath.i] objectAtIndex:0])
{
[searchArray addObject:str];
i++;
}
for (NSString *sTemp in searchArray)
{
NSString *txtToSearch =[[NSString alloc] initWithString:[sTemp substringWithRange:NSMakeRange(0,[searchText length])]];
if([[txtToSearch lowercaseString] isEqualToString:[searchText lowercaseString]])
{
[copyListOfItems addObject:sTemp];
}
}
[searchArray release];
searchArray = nil;
}
Also we want to know what you have written in your numberOfSections tableView Delegate.