Checkbox selecting other checkboxes when one is selected - iphone

I have created a custom class called Checkbox which changes its image on touch so that it gives a checkbox effect. However, when I click on one checkbox in the tableView, other checkboxes on seperate rows are selected too. Please could you tell me the problem with my code:
Checkbox.m
- (void)checkImages {
NSUInteger tag = [self tag];
BOOL val = [[NSUserDefaults standardUserDefaults] boolForKey:[NSString stringWithFormat:#"%i", tag]];
if (val == YES) {
[self setImage:[UIImage imageNamed:#"checkbox-pressed.png"] forState:UIControlStateNormal];
[[NSUserDefaults standardUserDefaults] setBool:NO forKey:[NSString stringWithFormat:#"%i", tag]];
}
else if (val == NO) {
[self setImage:[UIImage imageNamed:#"checkbox.png"] forState:UIControlStateNormal];
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:[NSString stringWithFormat:#"%i", tag]];
}
[[NSUserDefaults standardUserDefaults] synchronize];
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
if ([[[[event allTouches] anyObject] view] tag] == [self tag]) {
[self checkImages];
}
}
RootViewController:
- (void)viewDidLoad
{
//This will set a solid background color
self.tableView.backgroundColor = [UIColor blackColor];
self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
if (_checkboxArray == nil) {
[self setItemArray:[[NSMutableArray alloc] init]];
}
if (_cellTextArray == nil) {
[self setCellTextArray:[[NSMutableArray alloc] init]];
}
if (![[NSUserDefaults standardUserDefaults] boolForKey:kFL]) {
NSMutableArray *custArr = [[NSMutableArray alloc] init];
for (int i = 0; i < [_checkboxArray count]; i ++) {
CheckBox *c = (CheckBox *)[_checkboxArray objectAtIndex:i];
[c setImage:[UIImage imageNamed:#"checkbox.png"] forState:UIControlStateNormal];
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:[NSString stringWithFormat:#"%i", [c tag]]];
[custArr addObject:c];
}
[_checkboxArray release];
[_checkboxArray setArray:custArr];
[custArr release];
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:kFL];
[[NSUserDefaults standardUserDefaults] synchronize];
}
for (int i = 0; i < [textLabelArray count]; i++) {
NSDictionary *dict = [[NSDictionary alloc] initWithObjects:[NSArray arrayWithObjects:[textLabelArray objectAtIndex:i], [detailTextArray objectAtIndex:i], [cornLabelArray objectAtIndex:i], nil] forKeys:[NSArray arrayWithObjects:#"textLabel", #"detailTextLabel", #"cornerLabel", nil]];
[_cellTextArray addObject:dict];
[dict release];
}
for (int i = 0; i < [_cellTextArray count]; i++) {
CheckBox*btn = [[CheckBox alloc] init];
[btn setFrame:CGRectMake(0, 10, 40, 40)];
[btn setTag:i];
UIImage *img = [UIImage imageNamed:[[NSUserDefaults standardUserDefaults] boolForKey:[NSString stringWithFormat:#"%i", btn.tag]] ? #"checkbox.png":#"checkbox-pressed.png"];
[btn setImage:img forState:UIControlStateNormal];
[_checkboxArray addObject:btn];
[btn release];
}
[self.tableView reloadData];
[super viewDidLoad];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"CustomCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
CheckBox *btn;
UILabel *lab, *dlabl, *cornerLabel;
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
btn = (CheckBox *)[_checkboxArray objectAtIndex:indexPath.row];
[cell.contentView addSubview:btn];
//I added this code:
cell.textLabel.font = [UIFont fontWithName:#"Helvetica" size:12.0];
cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
cell.textLabel.numberOfLines = 3; // 0 means no max.
UIImageView* img = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:#"gradient7.png"]] autorelease];
[cell setBackgroundView:img];
lab = [[[UILabel alloc] initWithFrame:CGRectMake(40, 18, cell.contentView.frame.size.width-15, 22)] autorelease];
[lab setBackgroundColor:[UIColor clearColor]];
[lab setTextColor:[UIColor whiteColor]];
[lab setAdjustsFontSizeToFitWidth:YES];
[lab setTextAlignment:UITextAlignmentLeft];
[lab setTag:kTEXT_LABEL_TAG];
[cell.contentView addSubview:lab];
dlabl = [[[UILabel alloc] initWithFrame:CGRectMake(5, 54, cell.contentView.frame.size.width- 1, 22)] autorelease];
[dlabl setTextColor:[UIColor colorWithRed:1.0 green:0.80 blue:0.0 alpha:1.0]];
[dlabl setBackgroundColor:[UIColor clearColor]];
// [dlabl setAdjustsFontSizeToFitWidth:YES];
[dlabl setTextAlignment:UITextAlignmentLeft];
[dlabl setTag:kDETAIL_TEXT_LABEL_TAG];
[dlabl setFont:[UIFont systemFontOfSize:[lab font].pointSize - 3]];
[cell.contentView addSubview:dlabl];
cornerLabel = [[[UILabel alloc] initWithFrame:CGRectMake(cell.contentView.frame.size.width - 40, 19, 40, 20)] autorelease];
[cornerLabel setTextColor:[UIColor whiteColor]];
//[cornerLabel setFont:[UIFont systemFontOfSize:12]];
[cornerLabel setAdjustsFontSizeToFitWidth:YES];
[cornerLabel setBackgroundColor:[UIColor clearColor]];
[cornerLabel setTextAlignment:UITextAlignmentCenter];
[cornerLabel setTag:kCORNER_TEXT_LABEL_TAG];
[cell.contentView addSubview:cornerLabel];
[cornerLabel setAdjustsFontSizeToFitWidth:YES];
}
else {
lab = (UILabel *)[[cell contentView] viewWithTag:kTEXT_LABEL_TAG];
dlabl = (UILabel *)[[cell contentView] viewWithTag:kDETAIL_TEXT_LABEL_TAG];
cornerLabel = (UILabel *)[[cell contentView] viewWithTag:kCORNER_TEXT_LABEL_TAG];
btn = (CheckBox *)[[cell contentView] viewWithTag:kBTN_TAG];
}
NSDictionary *dict = [_cellTextArray objectAtIndex:indexPath.row];
lab.text = [dict objectForKey:#"textLabel"];
dlabl.text = [dict objectForKey:#"detailTextLabel"];
cornerLabel.text = [dict objectForKey:#"cornerLabel"];
if ([[NSUserDefaults standardUserDefaults] boolForKey:[NSString stringWithFormat:#"%d", indexPath.row]] == NO) {
[btn setImage:[UIImage imageNamed:#"checkbox-pressed.png"] forState:UIControlStateNormal];
}else {
[btn setImage:[UIImage imageNamed:#"checkbox.png"] forState:UIControlStateNormal];
}
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 80.0f;
}

You are using tableView dequeueReusableCellWithIdentifier:CellIdentifier]. This is a good thing, but it means that in your table view, you have only as many cells as you can see. When you scroll and a cell leaves the screen on one end, it will then be reused and reenter the screen from the other end. And of course, the cell still contains the same checkbox, so if it was checked when it left the screen it still will be, if not, it won't.
Solving this should be pretty straight forward. In your tableView:(UITableView *)tableView cellForRowAtIndexPath: you already fill the cell accordingly to the item which should be displayed there (lab.text = [dict objectForKey:#"textLabel"]; and so on). So all you have to to is to save the checkboxes state for every item in your tableview and restore it there.
Hope that helps!

Related

Looping in UITableViewCell

I m doing a quiz project where the number of questions and number of options for a questions are dynamic (taken from a service url).Maximum 5 options for a question(but may be decreased).I m displaying it in sectioned UITableView where each question and its options are displayed in one section.I m taking the objects in one section in a NSMutableArray and looping the options each time .But Im getting only the last option.
I couldnot understand why is it so ?
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *hlCellID=#"hlCellID";
UITableViewCell* hlcell=[tableView dequeueReusableCellWithIdentifier:hlCellID];
if(hlcell == nil)
{
hlcell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:hlCellID]autorelease];
hlcell.accessoryType = UITableViewCellAccessoryNone;
hlcell.selectionStyle = UITableViewCellSelectionStyleNone;
lblQuestion = [[UILabel alloc] initWithFrame:CGRectZero];
lblQuestion.tag = 1;
lblQuestion.backgroundColor = [UIColor clearColor];
[lblQuestion setFont:[UIFont fontWithName:#"Helvetica-Bold" size:14]];
[lblQuestion setLineBreakMode:NSLineBreakByWordWrapping];
[hlcell addSubview:lblQuestion];
lblanswers = [[UILabel alloc] initWithFrame:CGRectZero];
lblanswers.tag = 2;
lblanswers.backgroundColor = [UIColor clearColor];
[lblanswers setFont:[UIFont fontWithName:#"Helvetica-Bold" size:12]];
[lblanswers setLineBreakMode:NSLineBreakByWordWrapping];
[hlcell addSubview:lblanswers];
}
int section=indexPath.section;
NSMutableArray *sectionItems=[self.finalarray objectAtIndex:indexPath.section];
int n=[sectionItems count];
hlcell.selectionStyle = UITableViewCellSelectionStyleNone;
NSString *question = [NSString stringWithFormat:#"%#",[[sectionItems objectAtIndex:indexPath.row] objectForKey:#"Question"]];
CGSize constraint1 = CGSizeMake(320, 2000.0f);
CGSize size1 = [question sizeWithFont: [UIFont fontWithName:#"Helvetica-Bold" size:14] constrainedToSize:constraint1 lineBreakMode:NSLineBreakByWordWrapping];
lblQuestion = (UILabel *)[hlcell viewWithTag:1];
lblQuestion.text = [NSString stringWithFormat:#"%#",question];
[lblQuestion setNumberOfLines:0];
lblQuestion.frame = CGRectMake(10,25, size1.width, size1.height);
for(int j=1;j<n;j++)
{
NSLog(#"%#",[[sectionItems objectAtIndex:j] objectForKey:#"Description"]);
NSString *answer = [NSString stringWithFormat:#"%#",[[sectionItems objectAtIndex:j] objectForKey:#"Description"]];
CGSize constraint2 = CGSizeMake(320, 2000.0f);
CGSize size2 = [answer sizeWithFont: [UIFont fontWithName:#"Helvetica-Bold" size:14] constrainedToSize:constraint2 lineBreakMode:NSLineBreakByWordWrapping];
lblanswers = (UILabel *)[hlcell viewWithTag:2];
lblanswers.text = [NSString stringWithFormat:#"%#",answer];
[lblanswers setNumberOfLines:0];
lblanswers.frame = CGRectMake(10,20*j, size2.width, size2.height);
[hlcell.contentView addSubview:lblanswers];
}
return hlcell;
}
I couldn't understand how to set the frame for a lblanswers.
EDIT:
-(IBAction)checkboxClicked:(id)sender
{
NSMutableArray *arr1=[[NSMutableArray alloc]init];
NSIndexPath *indexPath = [self.tableView indexPathForCell:(UITableViewCell *)
[[sender superview] superview]];
NSLog(#"The section is %d", indexPath.section);
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
NSMutableArray *cellSection = [self.finalarray objectAtIndex:indexPath.section];
int tagID=[sender tag];
int divnum=0;
if(tagID<100)
divnum=10;
else
divnum=100;
int section=[sender tag]/divnum;
section-=1;
int itemId=[sender tag]%divnum;
if(itemId==selectedrowforCheckBox)
{
if(self.isChecked ==NO)
{
self.isChecked =YES;
[sender setImage:[UIImage imageNamed:#"checkbox_checked.png"] forState:UIControlStateNormal];
NSNumber* xWrapped = [NSNumber numberWithInt:itemId];
int m=[cellSection count]-1;
NSString *questionId=[[cellSection objectAtIndex:m-1]objectForKey:#"QId"];
NSMutableDictionary *hk=[[NSMutableDictionary alloc]init];
[hk setObject:xWrapped forKey:#"Ans"];
[hk setObject:questionId forKey:#"QId"];
[selectedOptionandQIdArray addObject:hk];
}
else
{
self.isChecked =NO;
[sender setImage:[UIImage imageNamed:#"checkbox_unchecked.png"]forState:UIControlStateNormal];
NSNumber* xWrapped = [NSNumber numberWithInt:itemId];
int m=[cellSection count]-1;
NSString *questionId=[[cellSection objectAtIndex:m-1]objectForKey:#"QId"];
for (int i=0;i<[selectedOptionandQIdArray count];i++)
{
NSString *qid=[[selectedOptionandQIdArray objectAtIndex:i]objectForKey:#"QId"];
if(xWrapped==[[selectedOptionandQIdArray objectAtIndex:i]objectForKey:#"Ans"] && [questionId isEqualToString:qid])
{
NSLog(#"nnd");
[selectedOptionandQIdArray removeObjectAtIndex:i];
}
}
}
selectedrowforCheckBox=itemId;
}
else
{
if(self.isChecked ==NO)
{
self.isChecked =YES;
[sender setImage:[UIImage imageNamed:#"checkbox_checked.png"] forState:UIControlStateNormal];
NSNumber* xWrapped = [NSNumber numberWithInt:itemId];
int m=[cellSection count]-1;
NSString *questionId=[[cellSection objectAtIndex:m-1]objectForKey:#"QId"];
NSMutableDictionary *hk=[[NSMutableDictionary alloc]init];
[hk setObject:xWrapped forKey:#"Ans"];
[hk setObject:questionId forKey:#"QId"];
[selectedOptionandQIdArray addObject:hk];
}
else
{
self.isChecked =NO;
[sender setImage:[UIImage imageNamed:#"checkbox_unchecked.png"]forState:UIControlStateNormal];
}
selectedrowforCheckBox=itemId;
}
}
You are doing it wrong. Break down the work in to two parts:
Before that create a dictionary in which each key is question and associated object is an array which contains all the answers.
number of sections = [dictionary count]
number of rows per section = [[dictionary valueForKey:[[dic allKeys] objectAtIndex:indexPath.section]] count]
Questions - create a custom view with UITextView and return that as header for each section and you can adjust the height by calculating and returning height based on question.
Answers - create a custom cell with UITextView and set the text based on section and row.
This strategy will not only simplify the code by given it a structure but also specify the detection of answers selected by user, as you can just store indexPath and check the section for question and row for answer selected by user.
U can download a sample code from here: http://www.saplogix.net/QA/sample.zip

Index tableview in iphone sdk

i have an indexed tableview with 8 arrays like
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
NSMutableArray *tempArray = [[NSMutableArray alloc] init];
[tempArray addObject:#"GEN"];
[tempArray addObject:#"1SA"];
[tempArray addObject:#"EST"];
[tempArray addObject:#"EZE"];
[tempArray addObject:#"NAH"];
[tempArray addObject:#"JOH"];
[tempArray addObject:#"COL"];
[tempArray addObject:#"REV"];
return tempArray;
}
and i get everything right,my problem is when i tap the cell it redirected to the another page with only first array value that is the value inside the [tempArray addObject:#"GEN"];and i tap the values in [tempArray addObject:#"1SA"];etc etc,i get the values inn the [tempArray addObject:#"GEN"];.my DidSelectRowAtIndexPath look like this
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
ChapterSelectionView *detailViewController = [[ChapterSelectionView alloc] initWithNibName:#"ChapterSelectionView" bundle:nil];
//detailViewController.firstString = firstString;
// ...
// Pass the selected object to the new view controller.
detailViewController.selectedIndex=indexPath.row;
detailViewController.selectedCountry = selectedCountry;
appDelegate.selectedBookIndex=indexPath.row;
self.hidesBottomBarWhenPushed=YES;
[self.navigationController pushViewController:detailViewController animated:YES];
[detailViewController release];
}
this is my complete tableview code
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
return index % 8;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [books count];
}
my viewdidload look like this
- (void)viewDidLoad {
[super viewDidLoad];
l
appDelegate=(Malayalam_BibleAppDelegate *)[[UIApplication sharedApplication] delegate];
s";
books = [[NSMutableArray alloc] init];
NSArray *biblearray1 = [NSArray arrayWithObjects:#"Genesis",
#"Exodus",
#"Leviticus",
#"Numbers",
#"Deuteronomy",
#"Joshua",
#"Judges",
#"Ruth", nil];
NSDictionary *bibledic1 = [NSDictionary dictionaryWithObject:biblearray1 forKey:#"Countries"];
NSArray *biblearray2 = [NSArray arrayWithObjects:#"1Samuel",
#"2Samuel",
#"1King",
#"2King",
#"1Chronicles",
#"2Chronicles",
#"Ezra",
#"Nehemiah", nil];
......etc etc
[books addObject:bibledic1];
[books addObject:bibledic2];
.....etc etc
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSDictionary *dictionary = [books objectAtIndex:section];
NSArray *array = [dictionary objectForKey:#"Countries"];
return [array count];
}
// Customize the appearance of table view cells.
- (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];
}
UIView *myBackView = [[UIView alloc] initWithFrame:cell.frame];
myBackView.backgroundColor = [UIColor brownColor];
// [myBackView setBackgroundColor:[UIColor colorWithRed:1 green:1 blue:0.75 alpha:1]];
cell.selectedBackgroundView = myBackView;
[myBackView release];
// Configure the cell.
// cell.textLabel.tag =row*1+col;
//First get the dictionary object
NSDictionary *dictionary = [books objectAtIndex:indexPath.section];
NSArray *array = [dictionary objectForKey:#"Countries"];
//NSString *cellValue = [array objectAtIndex:indexPath.row];
cell.textLabel.text =[array objectAtIndex:indexPath.row];
cell.textLabel.highlightedTextColor = [UIColor darkGrayColor];
//cell.textLabel.text = [books objectAtIndex:indexPath.row];
cell.textLabel.font = [UIFont fontWithName:#"Georgia" size:18.0];
cell.textLabel.textColor = [UIColor darkGrayColor];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;;
return cell;
}
how to get the correct values from tableview cell.
Thanks in advance.
EDIT
- (void)viewDidLoad {
[super viewDidLoad];
[[self navigationController] setNavigationBarHidden:YES animated:NO];
scrollView=[[UIScrollView alloc]initWithFrame:CGRectMake(0,49,320,480)];
appDelegate = (Malayalam_BibleAppDelegate *)[[UIApplication sharedApplication] delegate];
//self.navigationItem.title=[appDelegate.books objectAtIndex:selectedIndex];
chapterlabel.text = [appDelegate.books objectAtIndex:selectedIndex];
buttonArray =[[NSMutableArray alloc]initWithCapacity:0];
//self.view.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:#"bg10"]];
[self.view addSubview:scrollView];
}
-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:YES];
[[self navigationController] setNavigationBarHidden:YES animated:NO];
n=[DbHandler mNumberOfChaptersInBook:[appDelegate.books objectAtIndex:selectedIndex]];
int scrollViewHieght=n/6;
scrollView.contentSize = CGSizeMake(320,10+34*scrollViewHieght);
i=1;
int rowCount=n/6;
for(int row=0;row<=rowCount;row++){
for (int col = 0; col < 6; col++) {
if(i<=n){
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.titleLabel.textColor=[UIColor blueColor];
button.titleLabel.font = [UIFont fontWithName:#"Georgia" size:15.0];
[button setBackgroundImage:[UIImage imageNamed:#"tabs"] forState:UIControlStateNormal];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//button.frame=CGRectMake(col*52+5,row*34+50,50,32);
button.frame=CGRectMake(col*52+5,row*34+0,50,32);
[button addTarget:self action:#selector(ButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
[button setTitle:[NSString stringWithFormat:#"%d",i++] forState:UIControlStateNormal];
//button.titleLabel.font=[UIFont boldSystemFontOfSize:15];
button.titleLabel.textColor=[UIColor blackColor];
button.tag =row*6+col;
[buttonArray addObject:button];
[scrollView addSubview:[buttonArray objectAtIndex:row*6+col]];
//[self.view addSubview:button];
[button release];
}
}
}
}
you also need to send section number to the detailViewController. Depending on the section you have to select the required array.

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.

Crash after returning to tableview

So I am writing an app to read an rss feed, and display the contents in a tableview. It also lets the user play back mp3s that it finds for each item. Anyway the app seemed to be running fine before I started adding new views. Now every time I come back from a view and scroll around a bit, I get "Program received signal "SIGABRT"" or something similar.
here's most of the program:
- (IBAction)playAction:(id)sender
{
// Get row
UIButton *senderButton = (UIButton *)sender;
UITableViewCell *buttonCell =
(UITableViewCell *) [[senderButton superview] superview];
NSInteger buttonRow = [[self.tableView
indexPathForCell:buttonCell] row];
// Entry for row
RSSEntry *senderEntry = [_allEntries objectAtIndex:buttonRow];
// This is where _allEntries gets filled
- (void)requestFinished:(ASIHTTPRequest *)request {
[_queue addOperationWithBlock:^{
NSError *error;
GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:[request responseData]
options:0 error:&error];
if (doc == nil)
{
NSLog(#"Failed to parse %#", request.url);
}
else
{
NSMutableArray *entries = [NSMutableArray array];
[self parseRss:doc.rootElement entries:entries];
if ([_allEntries count] > 0) {
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
// Update
int i=0;
while (![[[_allEntries objectAtIndex:i] articleUrl] isEqualToString:[[entries objectAtIndex:i] articleUrl]])
{
[_allEntries insertObject:[entries objectAtIndex:i] atIndex:0];
i++;
}
[self.tableView reloadData];
}];
}
else
{
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
for (RSSEntry *entry in entries)
{
[_allEntries addObject:entry];
}
NSLog(#"entries:%d", [_allEntries count]);
[self.tableView reloadData];
}];
}
}
}];
}
- (void)viewDidLoad
{
[super viewDidLoad];
NSLog(#"View did load");
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh
target:self
action:#selector(refreshButton:)];
pauseImage = [UIImage imageNamed:#"pause_circle_small.png"];
playImage = [UIImage imageNamed:#"play_circle_small.png"];
player = nil;
isPlaying = NO;
self.title = #"Feed";
self.allEntries = [NSMutableArray array];
self.queue = [[[NSOperationQueue alloc] init] autorelease];
self.feed = [[NSString alloc] initWithString:#"http://site.org/rss/"];
[self refresh];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [_allEntries count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UILabel *mainLabel, *secondLabel;
UIButton *playBtn;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier] autorelease];
mainLabel = [[[UILabel alloc] initWithFrame:CGRectMake(42.0, 5.0, 250.0, 20.0)] autorelease];
mainLabel.tag = MAINLABEL_TAG;
mainLabel.font = [UIFont fontWithName:#"Arial-BoldMT" size:18.0];
mainLabel.textAlignment = UITextAlignmentLeft;
mainLabel.textColor = [UIColor blackColor];
mainLabel.highlightedTextColor = [UIColor whiteColor];
[cell.contentView addSubview:mainLabel];
secondLabel = [[[UILabel alloc] initWithFrame:CGRectMake(42.0, 27.0, 250.0, 15.0)] autorelease];
secondLabel.tag = SECONDLABEL_TAG;
secondLabel.font = [UIFont fontWithName:#"ArialMT" size:14.0];
secondLabel.textAlignment = UITextAlignmentLeft;
secondLabel.textColor = [UIColor colorWithRed:222.0/255.0 green:95.0/255.0
blue:199.0/255.0 alpha:1.0];
secondLabel.highlightedTextColor = [UIColor whiteColor];
[cell.contentView addSubview:secondLabel];
playBtn = [UIButton buttonWithType:UIButtonTypeCustom];
playBtn.tag = PLAYBTN_TAG;
playBtn.frame = CGRectMake(2.0, 6.0, playImage.size.width, playImage.size.height);
[playBtn setBackgroundImage:playImage forState:UIControlStateNormal];
//[playBtn setBackgroundImage:playImage forState:UIControlStateHighlighted];
[playBtn addTarget:self action:#selector(playTapped:)
forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:playBtn];
}
else
{
mainLabel = (UILabel *)[cell.contentView viewWithTag:MAINLABEL_TAG];
secondLabel = (UILabel *)[cell.contentView viewWithTag:SECONDLABEL_TAG];
playBtn = (UIButton *)[cell.contentView viewWithTag:PLAYBTN_TAG];
}
// Alternate bg color
if (indexPath.row%2 == 0) {
UIColor *altColor = [UIColor colorWithRed:230.0/255.0 green:230.0/255.0
blue:230.0/255.0 alpha:1];
mainLabel.backgroundColor = altColor;
secondLabel.backgroundColor = altColor;
}
else
{
UIColor *altColor = [UIColor colorWithRed:255.0 green:255.0
blue:255.0 alpha:1];
mainLabel.backgroundColor = altColor;
secondLabel.backgroundColor = altColor;
}
RSSEntry *entry = [_allEntries objectAtIndex:indexPath.row];
NSLog(#"Entry: %#", entry);
// Manage play button
if (entry == currEntry)
{
if(isPlaying)
{
[playBtn setBackgroundImage:pauseImage forState:UIControlStateNormal];
}
else
{
[playBtn setBackgroundImage:playImage forState:UIControlStateNormal];
}
}
else
[playBtn setBackgroundImage:playImage forState:UIControlStateNormal];
mainLabel.text = entry.articleTitle;
secondLabel.text = entry.articleArtist;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// Navigation logic may go here. Create and push another view controller.
DetailView *detailViewController = [[DetailView alloc] initWithNibName:#"DetailedView" bundle:[NSBundle mainBundle]];
RSSEntry *entry = [_allEntries objectAtIndex:[indexPath row]];
[self.navigationController pushViewController:detailViewController animated:YES];
detailViewController.songTitle.text = entry.articleTitle;
detailViewController.artistName.text = entry.articleArtist;
[entry release];
[detailViewController release];
}
- (void)dealloc
{
[player release];
player = nil;
[_queue release];
_queue = nil;
[_feed release];
_feed = nil;
[_allEntries release];
_allEntries = nil;
[super dealloc];
}
#end
Please Dont release any #synthesize variable. You should only release it in dealloc method
It's a wild guess, but you don't retain the images that you get in viewDidLoad:
pauseImage = [UIImage imageNamed:#"pause_circle_small.png"];
playImage = [UIImage imageNamed:#"play_circle_small.png"];
Either use retaining property and dot syntax or send each a retain.
AHAA!!! I was setting my RSSEntry to autorelease before putting them in the _allEntries array. They were getting dealloc'd when I changed views. Don't do that. Thanks for the help everyone. That was so simple, I feel dumb now.
please don't release the self.feed and also when unload or dealloc the view at that time put delegate nil means
tableview.delegate = nil;
this one is the main thing check after this i think u don't nil the delegate of tableview.
without line where you get crash its hard to tell, but most likely you accessing some object what was dealloc'ed
most likely its here
self.feed = [[NSString alloc] initWithString:#"http://site.org/rss/music"];
[self.feed release];
you releasing objects right away, but its hard to tell without knowing if you have retained property

how do we access values stored in NSMutableArray of NSMutableDictionary?

I have stored values in NsMutableDictionaries . ThenI stored all the dictionaries in NSMutable Array. I need to access the values ? How can I do that ?
-(void)viewDidLoad
{
[super viewDidLoad];
self.title = #"Library";
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:#"Close" style:UIBarButtonItemStyleBordered target:self action:#selector(close:)];
cells = [[NSMutableArray alloc] initWithObjects:#"dict1", #"dict2", #"dict3", #"dict4", #"dict5", #"dict6", nil];
dict1 = [[NSMutableDictionary alloc] initWithObjectsAndKeys:#"Mon, 01 Feb #2", #"date", #"0.7", #"time", #"1.2MB", #"size", #"200*200", #"pix", nil];
dict2 = [[NSMutableDictionary alloc] initWithObjectsAndKeys:#"Wed, 02 Mar #3", #"date", #"1.2", #"time", #"2.2MB", #"size", #"300*300", #"pix", nil];
dict3 = [[NSMutableDictionary alloc] initWithObjectsAndKeys:#"Tue, 03 Apr #5", #"date", #"1.7", #"time", #"2.5MB", #"size", #"240*240", #"pix", nil];
dict4 = [[NSMutableDictionary alloc] initWithObjectsAndKeys:#"Mon, 01 Feb #2", #"date", #"0.7", #"time", #"1.2MB", #"size", #"200*200", #"pix", nil];
dict5 = [[NSMutableDictionary alloc] initWithObjectsAndKeys:#"Mon, 10 Nov #5", #"date", #"2.7", #"time", #"4.2MB", #"size", #"200*400", #"pix", nil];
dict6 = [[NSMutableDictionary alloc] initWithObjectsAndKeys:#"Mon, 11 Dec #6", #"date", #"4.7", #"time", #"2.2MB", #"size", #"500*200", #"pix", nil];
//[cells addObject:dict1];
//[cells addObject:dict2];
//[cells addObject:dict3];
//[cells addObject:dict4];
//[cells addObject:dict5];
//[cells addObject:dict6];
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [cells count];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{ cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
//cell.contentView.frame = CGRectMake(0.0f, 0.0f, 320.0f, 80.0f);
[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
UIImageView *image1 = [[UIImageView alloc]init];
image1.frame = CGRectMake(0.0f, 0.0f, 80.0f, 80.0f);
image1.tag = tag7;
UILabel *dateLabel = [[UILabel alloc]init];
dateLabel.frame = CGRectMake(100.0f, 5.0f, 120.0f, 25.0f);
dateLabel.font = [UIFont fontWithName:#"Georgia" size:10];
dateLabel.tag = tag1;
UILabel *timeLabel = [[UILabel alloc] init];
timeLabel.frame = CGRectMake(100.0f, 30.0f, 40.0f, 25.0f);
timeLabel.font = [UIFont fontWithName:#"Georgia" size:10];
timeLabel.tag = tag2;
UILabel *sizeLabel = [[UILabel alloc] init];
sizeLabel.frame = CGRectMake(160.0f, 30.0f, 40.0f, 25.0f);
sizeLabel.font = [UIFont fontWithName:#"Georgia" size:10];
sizeLabel.tag = tag3;
UILabel *pixLabel = [[UILabel alloc] init];
pixLabel.frame = CGRectMake(220.0f, 30.0f, 40.0f, 25.0f);
pixLabel.font = [UIFont fontWithName:#"Georgia" size:10];
pixLabel.tag = tag4;
UILabel *shareLabel = [[UILabel alloc] init];
shareLabel.frame = CGRectMake(100.0f, 55.0f, 100.0f, 25.0f);
shareLabel.font = [UIFont fontWithName:#"Georgia" size:10];
shareLabel.tag = tag5;
UILabel *deleteLabel = [[UILabel alloc] init];
deleteLabel.frame = CGRectMake(220.0f, 55.0f, 100.0f, 25.0f);
deleteLabel.font = [UIFont fontWithName:#"Georgia" size:10];
deleteLabel.tag = tag6;
[cell.contentView addSubview:dateLabel];
[cell.contentView addSubview:timeLabel];
[cell.contentView addSubview:sizeLabel];
[cell.contentView addSubview:pixLabel];
[cell.contentView addSubview:shareLabel];
[cell.contentView addSubview:deleteLabel];
[cell.contentView addSubview:image1];
[dateLabel release];
[timeLabel release];
[sizeLabel release];
[pixLabel release];
[shareLabel release];
[deleteLabel release];
[image1 release];
}
// Set up the cell...
[(UILabel *)[cell viewWithTag:tag1] setText:[cells objectAtIndex:[dict1 objectForKey: #"date"]]];
[(UILabel *)[cell viewWithTag:tag2] setText:[cells objectAtIndex:[dict1 objectForKey: #"time"]]];
[(UILabel *)[cell viewWithTag:tag3] setText:[cells objectAtIndex:[dict1 objectForKey: #"size"]]];
[(UILabel *)[cell viewWithTag:tag4] setText:[cells objectAtIndex:[dict1 objectForKey: #"pix"]]];
[(UILabel *)[cell viewWithTag:tag5] setText:#"Share"];
[(UILabel *)[cell viewWithTag:tag6] setText:#"Delete"];
cell.imageView.image = [UIImage imageNamed:#"image2.png"];
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 80.0f;
}
I did in above way but it is not working. I know the mistake is at the accessing values. but, I could not get how to do it ?
Thank You.
You haven't stored the dictionaries at all—just the strings "dict1", "dict2", "dict3", and so on. The array initializer you're using should be something like
cells = [[NSMutableArray alloc] initWithCapacity:6];
I'm not sure why you've got all of the [cells addObject:dictionaryN]; lines commented out, because that's the correct way to add the dictionaries to the array; you also need to have a [dictionaryN release]; after each of them to prevent memory leaks.
To get the values out of the dictionaries in the array, you need to do something like this in your -tableView:cellForRowAtIndexPath: method:
NSDictionary *rowDictionary = [cells objectAtIndex:indexPath.row];
[(UILabel *)[cell viewWithTag:tag1] setText:[rowDictionary objectForKey:#"date"]];
[(UILabel *)[cell viewWithTag:tag2] setText:[rowDictionary objectForKey:#"time"]];
// etc.