How to store data in the tableView & update it next time - iphone

-(IBAction)btnSaveScore:(id)sender
{
if(!dictWinData)
dictWinData = [[NSMutableDictionary alloc] init];
array = [NSMutableArray arrayWithObjects:txt_EnterName.text,
[NSString stringWithFormat:#"%i",iTap], nil];
int increment = 0;
NSLog(#"array data is:--> %#",array);
for (int intWinData = 1; intWinData < [array count]; intWinData++)
{
[dictWinData setObject:array forKey:[NSString stringWithFormat:#"NameScore%d",increment]];
increment++;
}
}
This is the code to add my score of the game with name.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [dictWinData count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
ArrStr = [dictWinData valueForKey:[NSString stringWithFormat:#"NameScore%d",indexPath.row]];
UILabel *lblDayName = [[UILabel alloc] initWithFrame:CGRectMake(10, 50, 160, 21)];
lblDayName.text = [ArrStr objectAtIndex:0];
lblDayName.textColor = [UIColor blackColor];
lblDayName.font = [UIFont boldSystemFontOfSize:17.0];
lblDayName.backgroundColor = [UIColor clearColor];
[cell.contentView addSubview:lblDayName];
[lblDayName release];
UILabel *lblLow = [[UILabel alloc] initWithFrame:CGRectMake(180, 50, 40, 21)];
lblLow.text = [ArrStr objectAtIndex:1];
lblLow.textColor = [UIColor blackColor];
lblLow.font = [UIFont boldSystemFontOfSize:17.0];
lblLow.backgroundColor = [UIColor clearColor];
[cell.contentView addSubview:lblLow];
[lblLow release];
}
return cell;
}
This is storing name & score of the player but each time it displays only one record in the table.
It must show the last top ten scores in the list.
Main problem is that this is not storing & showing every score data.
Please guide me to solve this problem.
Thanks in advance.

You need to give the tag of each and every control that you want to display in UITableView and outside the cell==nil condition you need to retrieve that control with the specific tag and then give the text assignment to it.

You cannot use table view for storing data. Table view is an UI Element which can be used for display your data. UITableView reference.
For storing data you can use:
Core data
Sqlite
Plist

Related

Indexpath.row not working while getting record from NSMutableArray

I'm trying to load the data UITableViewwhich is coming from webservice. Everything is working fine. But, whenver the record is being displayed in UITableView using -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath delegate method i'm getting exception like below-
Here is my code -
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell; //= [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"Reuse_Cell"];
UILabel *label = nil;
cell = [tableView dequeueReusableCellWithIdentifier:#"Cell"];
cell.selectedBackgroundView = [[UIView alloc]init];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"Cell"];
label = [[UILabel alloc]initWithFrame:CGRectZero];
[label setLineBreakMode:UILineBreakModeWordWrap];
[label setNumberOfLines:1];
[label setFont:[UIFont fontWithName:#"Trebuchet MS" size:18]];
[label setTag:1];
label.backgroundColor = [UIColor clearColor];
label.textColor = [UIColor blackColor];
[[cell contentView] addSubview:label];
}
if (!label)
label = (UILabel *)[cell viewWithTag:1];
[label setText:[[webserviceRecords objectAtIndex:indexPath.row] objectForKey:#"catName"]];
[label setFrame:CGRectMake(10.0, 5.0, 225.0, 35.0)];
cell.selectedBackgroundView.backgroundColor = RGBACOLOR(151.0, 191.0, 69.0, 1.0);
cell.layer.borderWidth = 2.0f;
cell.layer.borderColor = RGBCOLOR(214, 218, 1).CGColor;
return cell;
}
My Array records -
http://pastie.org/7120406
Custom init method
- (id)initwithInteger:(NSInteger )integer
{
self = [super init];
if (self) {
startingpage = integer;
webserviceRecords = [[NSMutableArray alloc]init];
}
return self;
}
NumberofRowsInSection
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSLog(#"Row count - %d", [webserviceRecords count]);
return [webserviceRecords count];
}
You're setting the cell's selectedBackgroundView before checking that the cell has a value. You should check if the cell is nil first before doing that.
On a side note, you may find it much easier to display your array using the free Sensible TableView framework. The framework generates all the cells automatically from your array (including all the detail views), and can even fetch the data from the web service directly if you wish. Should save you a lot of headache and manual work. Hope this helps.
Really a silly mistake was there. I've parsed the JSON data directly into my NSMutableArray I've parsed like below first -
webserviceRecords = [NSJSONSerialization JSONObjectWithData:mutableData options:0 error:&error];
Instead of this i've fixed this like below -
NSArray *array = nil;
array = [NSJSONSerialization JSONObjectWithData:mutableData options:0 error:&error];
webserviceRecords = [array mutableCopy];
It helps me to fix my issue. Thanks for responsing my question.
Cheers!

UITableViewCell showing double embedded UITextfields

I have a UITableView with regular UITableViewCell, but I don't use any of UITableViewCell's lables. I just use the cell to embed a label and a UITextField to input some data. Problem is when you scroll up or scroll down and the UITableviewCell redraws itself, it draws an overlapping UITextFieldView over the old one and you see doubles! I'm thinking that maybe since I do put these UITextFields into a dictionary, it might save the textfield with a strong pointer, and try to make another one and just overlap. Anyone have any suggestions?
Here is my code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"ProductCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
NSDictionary *product = [self.products objectAtIndex:indexPath.row];
NSDictionary *orderpoint = [self.orderpoints objectAtIndex:indexPath.row];
cell.textLabel.text = #""; //black out text
CGFloat calculatedHeight = [self tableView:tableView heightForRowAtIndexPath:indexPath];
UILabel *productLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, cell.bounds.size.width - 50.0, calculatedHeight)];
productLabel.text = [[NSString alloc] initWithFormat:#"%#. %#",
[orderpoint objectForKey:#"sequence_nr"], [product objectForKey:#"name"]];
//word wrapping
productLabel.lineBreakMode = UILineBreakModeWordWrap;
productLabel.numberOfLines = 0; //infinite number of lines
productLabel.font = [UIFont fontWithName:#"Helvetica" size:14.0];
[cell.contentView addSubview:productLabel];
//create the cell's textfield
UITextField *cellTextField = [[UITextField alloc] initWithFrame:CGRectMake(cell.bounds.size.width - 50, cell.bounds.size.height - 30, 50, calculatedHeight - 20)];
cellTextField.adjustsFontSizeToFitWidth = YES;
cellTextField.textColor = [UIColor blackColor];
cellTextField.keyboardType = UIKeyboardTypeNumberPad; // will only need to end a count
cellTextField.returnKeyType = UIReturnKeyDone; // TODO make it go to the next items key, or make it exit out
cellTextField.backgroundColor = [UIColor whiteColor];
cellTextField.textAlignment = UITextAlignmentLeft; //align to the right
//cellTextField.delegate = self; //will need to set delegate, maybe
cellTextField.clearButtonMode = UITextFieldViewModeNever;
cellTextField.enabled = YES;
cellTextField.borderStyle = UITextBorderStyleRoundedRect; //add bezel rounded look to textfield
cellTextField.delegate = self;
[cell.contentView addSubview: cellTextField]; //add the textfield to the cell
// save to dictionary, using a dictionary because not certain if this is created in order to use an Array
[self.textFieldDict setObject:cellTextField forKey:[[NSNumber alloc] initWithInteger:indexPath.row]];
return cell;
}
You have not initialized your cell.Try this:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"ProductCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
//It will check whether cell in there or not, then deque the cell...
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
NSDictionary *product = [self.products objectAtIndex:indexPath.row];
NSDictionary *orderpoint = [self.orderpoints objectAtIndex:indexPath.row];
cell.textLabel.text = #""; //black out text
CGFloat calculatedHeight = [self tableView:tableView heightForRowAtIndexPath:indexPath];
UILabel *productLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, cell.bounds.size.width - 50.0, calculatedHeight)];
productLabel.text = [[NSString alloc] initWithFormat:#"%#. %#",
[orderpoint objectForKey:#"sequence_nr"], [product objectForKey:#"name"]];
//word wrapping
productLabel.lineBreakMode = UILineBreakModeWordWrap;
productLabel.numberOfLines = 0; //infinite number of lines
productLabel.font = [UIFont fontWithName:#"Helvetica" size:14.0];
[cell.contentView addSubview:productLabel];
//create the cell's textfield
UITextField *cellTextField = [[UITextField alloc] initWithFrame:CGRectMake(cell.bounds.size.width - 50, cell.bounds.size.height - 30, 50, calculatedHeight - 20)];
cellTextField.adjustsFontSizeToFitWidth = YES;
cellTextField.textColor = [UIColor blackColor];
cellTextField.keyboardType = UIKeyboardTypeNumberPad; // will only need to end a count
cellTextField.returnKeyType = UIReturnKeyDone; // TODO make it go to the next items key, or make it exit out
cellTextField.backgroundColor = [UIColor whiteColor];
cellTextField.textAlignment = UITextAlignmentLeft; //align to the right
//cellTextField.delegate = self; //will need to set delegate, maybe
cellTextField.clearButtonMode = UITextFieldViewModeNever;
cellTextField.enabled = YES;
cellTextField.borderStyle = UITextBorderStyleRoundedRect; //add bezel rounded look to textfield
cellTextField.delegate = self;
[cell.contentView addSubview: cellTextField]; //add the textfield to the cell
return cell;
}
Either don't use reusability and always alloc the cell at each time or
make a check after dequeue (like this)
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell==nil)
{
// make text field and label an add tag
}
//and outside this by using tag fetch the labels and textField and clear the textFields.
You forgot to put the condition like this:
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefaultreuseIdentifier:CellIdentifier];
}
Used this as a reference: add subviews to UITableViewCell
I just first checked to see if this view was added from before, and if it was, then don't add it again. It has nothing to do with the cell being nil. Unless I missed something? all I know is that this seems to be working fine, now.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"ProductCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
NSDictionary *product = [self.products objectAtIndex:indexPath.row];
NSDictionary *orderpoint = [self.orderpoints objectAtIndex:indexPath.row];
cell.textLabel.text = #""; //black out text
CGFloat calculatedHeight = [self tableView:tableView heightForRowAtIndexPath:indexPath];
UILabel *productLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, cell.bounds.size.width - 50.0, calculatedHeight)];
productLabel.text = [[NSString alloc] initWithFormat:#"%#. %#",
[orderpoint objectForKey:#"sequence_nr"], [product objectForKey:#"name"]];
//word wrapping
productLabel.lineBreakMode = UILineBreakModeWordWrap;
productLabel.numberOfLines = 0; //infinite number of lines
productLabel.font = [UIFont fontWithName:#"Helvetica" size:14.0];
[cell.contentView addSubview:productLabel];
if (![cell viewWithTag:1])
{
//create the cell's textfield
UITextField *cellTextField = [[UITextField alloc] initWithFrame:CGRectMake(cell.bounds.size.width - 50, cell.bounds.size.height - 30, 50, calculatedHeight - 20)];
cellTextField.adjustsFontSizeToFitWidth = YES;
cellTextField.textColor = [UIColor blackColor];
cellTextField.keyboardType = UIKeyboardTypeNumberPad; // will only need to end a count
cellTextField.returnKeyType = UIReturnKeyDone; // TODO make it go to the next items key, or make it exit out
cellTextField.backgroundColor = [UIColor whiteColor];
cellTextField.textAlignment = UITextAlignmentLeft; //align to the right
cellTextField.delegate = self; //will need to set delegate, maybe
cellTextField.clearButtonMode = UITextFieldViewModeNever;
cellTextField.enabled = YES;
cellTextField.borderStyle = UITextBorderStyleRoundedRect; //add bezel rounded look to textfield
cellTextField.delegate = self;
cellTextField.tag = 1; //set tag to 1
[cell.contentView addSubview: cellTextField]; //add the textfield to the cell
// save to dictionary, using a dictionary because not certain if this is created in order to use an Array
[self.textFieldDict setObject:cellTextField forKey:[[NSNumber alloc] initWithInteger:indexPath.row]];
}
return cell;
}

Returning more cells in a UITableView

I am using MGTwitterEngine and have almost EVERYTHING figured out, but for some reason I cannot figure out how to return more tweets in my timeline! It receives around 20 tweets by the method I am using and if I add a integer for example: return count = 100;, I can tell I now have 100 cells when it loads and by the scroll indicator but when I scroll to that 18- 19 cell I get this error:
SIGABRT
-[NSMutableArray objectAtIndex:]: index 20 beyond bounds [0 .. 19]'
* Call stack at first throw:
I know what it means: theres no more information to receive at cell 20. I'm baffled and went in and out of MGTwitterEngine looking for a default tweet count but I can't find it. I am using the dump to create my NSStrings and the dump only seems to give around 20 tweets per login. Please help, any suggestions are good in my book! Thank you!
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
int count = [tweets count];
// Return just enough cells to fill the screen during loading ....
if (count == 0)
count = MyCustomRowCount;
else {
//Here is where I think I need to add a else return integer but dont know how
}
return count;
return [tweets count];
return [authors count];
return [avatarsURL count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *identifier = #"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (cell == nil) {
[cell autorelease];
}
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"cell"]autorelease];
/*
//Here it adds a nice shadow to the table view but will crash on rotation and send a
wird dump !!!????
tableView.layer.shadowColor = [[UIColor blackColor] CGColor];
tableView.layer.shadowOffset = CGSizeMake(1.0f, 1.0f);
tableView.layer.shadowRadius = 8.0f;
tableView.layer.shadowOpacity = 1.0f;
*/
[cell.textLabel setNumberOfLines:1];
[cell.textLabel setText:[(Tweet*)[authors objectAtIndex:indexPath.row] author]];
[cell.detailTextLabel setText:[(Tweet*)[tweets objectAtIndex:indexPath.row] tweet]];
[cell.detailTextLabel setNumberOfLines:10];
[cell.textLabel setTextColor:[UIColor darkGrayColor]];
[cell.textLabel setShadowColor:[UIColor whiteColor]];
[cell.textLabel setShadowOffset:CGSizeMake(0.5, 0.5)];
[cell.detailTextLabel setTextColor:[UIColor blackColor]];
//[cell.detailTextLabel setText:[(Tweet*)[retweetCount objectAtIndex:indexPath.row]
reTweetCount]];
[cell.textLabel setUserInteractionEnabled:YES];
[cell.contentView setMultipleTouchEnabled:YES];
// cell.text = [[NSString alloc] initWithFormat:#"Cell :%i", indexPath.row];
// Here we use the new provided setImageWithURL: method to load the web image with
SDWebImageManager
[cell.imageView setImageWithURL:[NSURL URLWithString:[(Tweet*)[avatarsURL
objectAtIndex:indexPath.row]avatarURL]]
placeholderImage:[UIImage imageNamed:#"avatar.png"]];
//add gradient to cell
UIImage *gradient = [UIImage imageNamed:#"gradientcell2.png"];
UIImageView *cellimage = [[UIImageView alloc] initWithImage:gradient];
cellimage.contentMode = UIViewContentModeScaleToFill;
cell.backgroundView = cellimage;
[cellimage release];
UIImage *selectedGradient = [UIImage imageNamed:#"selectedcell.png"];
UIImageView *selectedCell = [[UIImageView alloc] initWithImage:selectedGradient];
selectedCell.contentMode = UIViewContentModeScaleToFill;
cell.selectedBackgroundView = selectedCell;
[tableView setBackgroundColor:[UIColor clearColor]];
return cell;
}
//get cell accessory
-(UITableViewCellAccessoryType)tableView:(UITableView *)tableView
accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath {
if(indexPath.row < [tweets count]){
}
return UITableViewCellAccessoryDisclosureIndicator;
}
// custom hieght
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath {
return 80;
}
//select tweet bring to detail view ..... Also bring in the Users information who made the tweet!
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath {
//Get the selected tweets
NSString *selectedTweet = [(Tweet*)[tweets objectAtIndex:indexPath.row] tweet];
NSString *selectedUser = [(Tweet*)[tweets objectAtIndex:indexPath.row] author];
NSString *selectedUserInfo = [(Tweet*)[tweets objectAtIndex:indexPath.row] user];
NSString *retweetCount = [(Tweet*)[tweets objectAtIndex:indexPath.row] reTweetCount ];
// NSString *selectedUserFriendsCount = [(Tweet*)[tweets objectAtIndex:indexPath.row] userFriendsCount];------HUH? NO soup for ME!
NSString *selectedUserFollowersCount = [(Tweet*)[tweets objectAtIndex:indexPath.row] userFollowersCount];
//Initialize the detail view controller and display it.
TwitterDetailViewController*dvController = [[TwitterDetailViewController alloc]
initWithNibName:#"TwitterDetailViewController" bundle:[NSBundle mainBundle]];
dvController.selectedTweet = selectedTweet;
dvController.selectedUser = selectedUser;
dvController.selectedUserInfo = selectedUserInfo;
// dvController.selectedUserFriendsCount = selectedUserFriendsCount;------Doesnt reconize the call for some odd reason!
dvController.selectedUserFollowersCount = selectedUserFollowersCount;
dvController.retweetCount = retweetCount;
dvController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
[self presentModalViewController:dvController animated:YES];
//[self.navigationController pushViewController:webController animated:YES];-------would rather use navagation controller for several obvious reasons
[dvController release];
dvController = nil;
}
UITableView doesn't it like it when you gave it something inconsistant. If you change the model, you need to call [tableView reloadData] or if you want to animate the changes call [tableView beingUpdate][tableView endUpdate] with all the insert/remove cell operations in the middle.
On another note, I'm not sure why you doing here:
NSString *identifier = #"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (cell == nil) {
[cell autorelease];
}
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:#"cell"];
[cell autorelease];
First if (cell == nil), calling auto release on it won't do anything.
The reuse identifier thing is a flyweight pattern. If dequeueReusableCellWithIdentifier: returns nil, it means it doesn't have a cell object in the pool for you to use and you should alloc a new one for it. dequeueReusableCellWithIdentifier also already returns an autorelease object.
Instead try this:
NSString *identifier = #"mytweetcell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier] autorelease];
}

problem with cellForRowAtIndexPath method in UITableView iphone (indexPath.row is null)

Table view cell management has driving me crazy from past two days. Please check the code below and I will explain you the problem in detail..
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
UILabel *nameLabel,*sugarLabel,*searchNameLabel,*searchSugarLabel;
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
CGFloat width = [UIScreen mainScreen].bounds.size.width - 50;
CGFloat height = 20;
CGRect frame = CGRectMake(10.0f, 10.0f, width, height);
if(isSearchOn)
{
searchNameLabel = [[UILabel alloc] initWithFrame:frame];
searchNameLabel.textColor = [UIColor blackColor];
searchNameLabel.backgroundColor = [UIColor clearColor];
searchNameLabel.textAlignment = UITextAlignmentLeft;
searchNameLabel.font = [UIFont systemFontOfSize:14.0f];
searchNameLabel.tag=260;
[cell.contentView addSubview:searchNameLabel];
[searchNameLabel release];
searchSugarLabel= [[UILabel alloc] initWithFrame:frame];
searchSugarLabel.textColor = [UIColor blackColor];
searchSugarLabel.backgroundColor = [UIColor clearColor];
searchSugarLabel.textAlignment = UITextAlignmentLeft;
searchSugarLabel.font = [UIFont systemFontOfSize:14.0f];
searchSugarLabel.tag=160;
[searchSugarLabel setHidden:YES];
[cell.contentView addSubview:searchSugarLabel];
[searchSugarLabel release];
}
else{
nameLabel = [[UILabel alloc] initWithFrame:frame];
nameLabel.textColor = [UIColor blackColor];
nameLabel.backgroundColor = [UIColor clearColor];
nameLabel.textAlignment = UITextAlignmentLeft;
nameLabel.font = [UIFont systemFontOfSize:14.0f];
nameLabel.tag=60;
[cell.contentView addSubview:nameLabel];
[nameLabel release];
sugarLabel= [[UILabel alloc] initWithFrame:frame];
sugarLabel.textColor = [UIColor blackColor];
sugarLabel.backgroundColor = [UIColor clearColor];
sugarLabel.textAlignment = UITextAlignmentLeft;
sugarLabel.font = [UIFont systemFontOfSize:14.0f];
sugarLabel.tag=160;
[sugarLabel setHidden:YES];
[cell.contentView addSubview:sugarLabel];
[sugarLabel release];
}
}
else {
if(isSearchOn)
{
searchNameLabel=(UILabel *)[cell.contentView viewWithTag:260];
searchSugarLabel=(UILabel *)[cell.contentView viewWithTag:160];
}
else{
nameLabel=(UILabel *)[cell.contentView viewWithTag:60];
sugarLabel=(UILabel *)[cell.contentView viewWithTag:160];
}
}
if (isSearchOn) {
cellValue = [searchResult objectAtIndex:indexPath.row];
searchSugarLabel.text=cellValue.sugarId;
NSString *searchText = [NSString stringWithFormat:#"%# %#", cellValue.firstName, cellValue.lastName];
searchNameLabel.text=searchText;
NSLog(#"%#",searchNameLabel.text);
NSLog(#"%#",searchSugarLabel.text);
}
else {
NSString *contact=[contactKeys objectAtIndex:[indexPath section]];
NSArray *contactSection=[contactNames objectForKey:contact];
sugar=[db getSugarId:#"Contacts" bySection:contact andIndex:indexPath.row];
NSString *cellText = [contactSection objectAtIndex:[indexPath row]];
// split the text by the : to get an array containing { "AAA", "BBB" }
NSArray *splitText = [cellText componentsSeparatedByString:#":"];
// form a new string of the form "BBB AAA" by using the individual entries in the array
NSString *contactText = [NSString stringWithFormat:#"%# %#", [splitText objectAtIndex:1], [splitText objectAtIndex:0]];
nameLabel.text = contactText;
sugarLabel.text = sugar;
}
return cell;
}
Contacts is a class which has the properties firstName,lastName and sugar id in it..I am assigning the properties of a contacts class to the variables in the database method and returning an array of contact objects. searchResult is now an array of contact objects.The problem is when I logged the contents on the console the database gets everything in it and returns an array of contacts.The contacts in the searchResult points to different memory locations but when I try to debug the cellForRowAtIndexPath method after it gets 6 contacts..the 7th contact points to the same memory location as the 1st and it repeats thus in the searchNameLabel.text it returns a null and indexPath points to nil...I think it is cell re use issue and I accept that I am very bad in that..I need to figure this out as I am going to finish off my project with this...please guys help me...
This happens only when I try to search for the contacts. It works fine when I try to load all the contacts onto the table..
You are initializing your subviews in the if(cell== nil) block, but in the corresponding else-block, you overwrite them again.
You should rethink your design: Do not load different views by searchon, but set their properties depending on searchon
if(cell == nil){
//do all initializing
}
if(searchon){
//set view/label properties for searching style
} else {
//set view/label properties for not-searching style
}
another approach could be to have totally separated NIB files for the searchon/!searchon
if(searchon){
static NSString *SearchOnCellIdentifier = #"SearchOnCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: SearchOnCellIdentifier];
if (cell == nil){
//load cell from extra nib
}
} else {
static NSString *SearchOFFCellIdentifier = #"SearchOFFCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: SearchOFFCellIdentifier];
if (cell == nil){
//load cell from extra nib
}
}
NOTE: I never did that and it is not tested.

UITableViewCell uses value from other cells

I have problem with using dequeueReusableCellWithIdentifier method. Whenever I use this one, one cell would display its own value and value that does not belong to it. This first and second images show the problem, while the third image shows the proper data.The problem seems to be caused by old value not being wiped off and the new value being added on top if it. Which seems very strange.
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell =nil ;
if(indexPath.row==0){
cell = [[[UITableViewCell alloc]init]autorelease];
}else {
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
}
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
NSMutableArray *rowArray = [results objectAtIndex:indexPath.section];
NSString *value=nil;
if (indexPath.section==0) {
// the row in the 0th section is patient's sticky
value = [rowArray objectAtIndex:indexPath.row];
cell.textLabel.text = value;
}else {
//the row in the 1th section are lab tests
//here rowArray is tableRecords
NSArray *rowrecordTemp = [rowArray objectAtIndex:indexPath.row];
UILabel *label= [[UILabel alloc]initWithFrame:CGRectMake(5, 0, 130, tableView.rowHeight-5) ];
value = [rowrecordTemp objectAtIndex:0];
label.text= value;
[cell.contentView addSubview:label];
[label release];
label = nil;
label = [[UILabel alloc] initWithFrame:CGRectMake(140, 0, 50.0,
tableView.rowHeight-10)];
value = [rowrecordTemp objectAtIndex:1];
label.text = value;
[cell.contentView addSubview:label];
[label release];
label = nil;
label = [[UILabel alloc] initWithFrame:CGRectMake(190, 0, 90, tableView.rowHeight-10)];
value = [rowrecordTemp objectAtIndex:2];
label.text = value;
[cell.contentView addSubview:label];
[label release];
label = nil;
NSLog(#"%#\t\t%#\t\t\t\t\n%#",[rowrecordTemp objectAtIndex:0] ,[rowrecordTemp objectAtIndex:1],[rowrecordTemp objectAtIndex:2]);
}
NSString *fontname = cell.textLabel.font.fontName;
cell.textLabel.font = [UIFont fontWithName:fontname size:16];
cell.textLabel.numberOfLines = 0;
return cell;
}
Table view cells are shared in memory. When you dequeue a new one, it will have the value of an old one (I think the last one to be dequeued). You have to clear it of its old contents to display its new contents.
If you're doing something along the lines of cell.textLabel.text = [arr objectAtIndex:indexPath.row] there's no problem because the text will simply be replaced. If you have a custom view or something more complicated, you have to completely replace the view.
When (section != 0) you're adding new UILabels to the UITableViewCell. Everytime a cell is dequeued, new labels are added to it. You should either remove the old labels, or change the text of the old label instead of creating a new one.