Index tableview in iphone sdk - iphone

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.

Related

Update Data and show it on UITableView iOS

I have a problem: update data in UITableView. I want to get new data from parseXML that response from Server and them update new data to UITableView. **I used beloww code, but it does not show new data on Table View. I wrote a UpdateArray() function to check new data and then I compare 2 Array,if diff [Array count] then I call [tableview reloadData];
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [temp count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 90;
}
- (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];
UILabel *FileNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 100, 30)];
FileNameLabel.backgroundColor = [UIColor clearColor];
FileNameLabel.font = [UIFont fontWithName:#"Helvetica" size:16];
FileNameLabel.font = [UIFont boldSystemFontOfSize:16];
FileNameLabel.textColor = [UIColor blackColor];
NSLog(#"Reseversed TEMP array %#",temp);
FileNameLabel.text =[temp objectAtIndex:indexPath.row];
[cell.contentView addSubview: FileNameLabel];
[FileNameLabel release];
UILabel *UploadTimeLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 20, 300, 25)];
UploadTimeLabel.backgroundColor = [UIColor clearColor];
UploadTimeLabel.font = [UIFont fontWithName:#"Helvetica" size:14];
UploadTimeLabel.textColor = [UIColor grayColor];
UploadTimeLabel.text = [UploadTimeArray objectAtIndex:indexPath.row];
[cell.contentView addSubview: UploadTimeLabel];
[UploadTimeLabel release];
UILabel *CompleteLabel = [[UILabel alloc] initWithFrame:CGRectMake(140, 12, 170, 25)];
CompleteLabel.backgroundColor = [UIColor clearColor];
CompleteLabel.font = [UIFont fontWithName:#"Helvetica" size:14];
CompleteLabel.textColor = [UIColor darkGrayColor];
CompleteLabel.text =#"Completed";
CompleteLabel.textAlignment = NSTextAlignmentRight;
[cell.contentView addSubview: CompleteLabel];
[CompleteLabel release];
}
return cell;
}
UpdateArray()
-(void)updateArray{
while (loop)
{
[NSThread sleepForTimeInterval:4.0];
[FileCompletedArray removeAllObjects];
// [temp removeAllObjects];
....
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:afRequest];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success");
NSString * parsexmlinput = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(#"Response in Loop CompleteView: %#", parsexmlinput);
// dispatch_async(dispatch_get_main_queue(), ^{
[self parseXMLFile:parsexmlinput];
NSLog(#"File Completed array: %#", FileCompletedArray);
NSLog(#"File Temp out array: %#", temp);
NSLog(#"File Completed count: %lu",(unsigned long)[ FileCompletedArray count]);
NSLog(#"File Temp out count: %lu", (unsigned long)[temp count]);
// NSLog(#"State: %#", state);
if([FileCompletedArray count ] != [temp count])
{
[temp removeAllObjects];
temp= [FileCompletedArray mutableCopy];
[_tableView reloadData];
}
else
{
NSLog(#"2 array equal");
}
//});
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"error: %#", error);
}
];
[httpClient enqueueHTTPRequestOperation:operation];
}
}
Can you help me? Thanks in advance.
I dont See that you call reloadData.
EDIT:
You must check that
1-Temp is having objects i mean that [temp count] is not returning zero.
2-The if condition that checks the two arrays is triggered . I mean that reload data is called.
3-You can make a breakpoint after cell.contetview addsubview and check what the cell contain now?
before you call
[_tableView reloadRowsAtIndexPaths:[_tableView indexPathsForVisibleRows]
withRowAnimation:UITableViewRowAnimationNone];
you have to call
[_tableView beginUpdates];
...
[_tableView endUpdates];
or call
[_tableView reloadData];
If you refresh table view then try this line & check:
[[self mytableview] reloadData];
mytableview is obj of tableview you give here your tableview object.

Alphabetically sorting the contacts inside a Section header in a UItableview

I have an issue of alphabetically sorting the contacts picked from the address book into section headers . I can arrange them alphabetically without the section headers but how to put them according to the names of the contacts ? I do not want to use the NSDictionary as I am able to do the sorting without it. Please view the code below :-
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [arrayForLastName count];
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
return [[alphabets sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)] objectAtIndex:section];
}
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{
return [NSArray arrayWithObjects:#"A",#"B",#"C",#"D",#"E",#"F",#"G",#"H",#"I",#"J",#"K",#"L",#"M",#"N",#"O",#"P",#"Q",#"R",#"S",#"T",#"U",#"V",#"W",#"X",#"Y",#"Z", nil];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [arrayForLastName count];
}
Any help would be appreciated thanx :)
You can achieve this in following way -
1.Create an index array that contains all the required index -
NSArray *indexArray = [NSArray arrayWithObjects:#"A",#"B",#"C",#"D",#"E",#"F",#"G",#"H",#"I",#"J",#"K",#"L",#"M",#"N",#"O",#"P",#"Q",#"R",#"S",#"T",#"U",#"V",#"W",#"X",#"Y",#"Z", nil];
2.For Each index you need to have an array that will display row for those sections. SO you can have a dictionary that contain an array corresponding to each index.
Check this tutorial, it will help you in implementing this- http://www.icodeblog.com/2010/12/10/implementing-uitableview-sections-from-an-nsarray-of-nsdictionary-objects/
Try this code in table delegate methode.
1) - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [dataArray1 count];
}
return number of section in your table view.
2) -(NSMutableArray *)selectedarray:(NSString *)countrynmae
{
NSString *strQuery=[NSString stringWithFormat:#" select * from Globle where Country='%#'",countrynmae];
NSMutableArray *dataarray=[Database executeQuery:strQuery];
return dataarray;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSDictionary *dict =[dataArray1 objectAtIndex:section];
NSString *strcountryname=[dict objectForKey:#"Country"];
NSMutableArray *arr6 = [self selectedarray:strcountryname ];
return [arr6 count];
}
Return number of row in particular section
3) - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
// create the parent view that will hold header Label
UIView* customView = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 300.0, 44.0)];
// create the button object
UILabel * headerLabel = [[UILabel alloc] initWithFrame:CGRectZero];
headerLabel.backgroundColor = [UIColor clearColor];
headerLabel.opaque = NO;
headerLabel.textColor = [UIColor whiteColor];
headerLabel.font = [UIFont boldSystemFontOfSize:16];
headerLabel.frame = CGRectMake(20.0, -14.0, 300.0, 30.0);
NSDictionary *dict =[dataArray1 objectAtIndex:section];
headerLabel.text=[dict objectForKey:#"Country"];
headerLabel.textColor=[UIColor redColor];
[customView addSubview:headerLabel];
return customView;
}
set header name for section
4) - (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];
cell.textLabel.textColor=[UIColor whiteColor];
cell.backgroundColor=[UIColor clearColor];
}
NSDictionary *dict =[dataArray1 objectAtIndex:indexPath.section];
NSString *countryname = [dict objectForKey:#"Country"];
NSString *strQuery = [NSString stringWithFormat:#"Select * from Globle where Country = '%#'",countryname];
NSMutableArray *arr = [Database executeQuery:strQuery];
NSDictionary *dict1 = [arr objectAtIndex:indexPath.row];
cell.textLabel.text=[dict1 objectForKey:#"Name"];
cell.textLabel.numberOfLines=1;
cell.textLabel.textColor=[UIColor blackColor];
cell.backgroundColor=[UIColor clearColor];
cell.textLabel.textAlignment=UITextAlignmentCenter;
NSString *strImage=[dict1 objectForKey:#"ImageName"];
UIImageView *imageView1 = [[UIImageView alloc] init];
UIImage *image1 = [[UIImage alloc] initWithContentsOfFile:
[[NSBundle mainBundle] pathForResource:strImage ofType:#"jpg"]];
imageView1.image = image1;
imageView1.frame = CGRectMake(6,2,50,42); // position it to the middle
[cell.contentView addSubview:imageView1];
return cell;
[tbl reloadData];
}
return cell in uitable view

Objective-C: 2 UItableViews displayed

I am sorry for pasting a big chunk of code but i really want to get it work;
This app is supposed to be placing a UItableView on a screen.
Somehow this code is calling tableview methods twice and creating duplicate tables.
Do you have any suggestion what I can do to fix this behaviour?
Thanks in advance.
UITableView:
- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section
{
NSLog(#"-------------numberOfRowsInSection---------------");
NSLog(#"qtext =%d",[qtext count]);
return [qtext count];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;
{
return 1;
}
-(void)insertDeviders{
UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 100, 200, 100)];
myLabel.text = #"About you";
[cell addSubview:myLabel];
}
//Return cellheight
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
NSLog(#"-------------heightforrowatindexpath---------------");
dict = [qtext objectAtIndex:[indexPath row]];
NSDictionary *dict2 = [qtype objectAtIndex:[indexPath row]];
type = [[dict2 allKeys] objectAtIndex:0];
NSString *text = [[dict allKeys] objectAtIndex:0];
CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);
CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
CGFloat height = MAX(size.height, 44.0f);
thisheight= height + (CELL_CONTENT_MARGIN * 2) + 40;
NSLog(#"thisheight=%d",thisheight);
NSString *q = [NSString stringWithFormat:#"%d", thisheight];
[arrAllheight addObject:[NSString stringWithFormat:#"%#",q]];
if([type isEqualToString:#"devider"]){thisheight=28;}
NSLog(#"dict=%#",dict);
NSLog(#"thisheight=%d",thisheight);
return thisheight;
}
Populate cell:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"-------------cellForRowAtIndexPath---------------");
cell_id = [qid objectAtIndex:[indexPath row] ];
static NSString *CellIdentifier = #"Cell";
label = nil;
cell = (UITableViewCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
// if(![cell_id intValue]==0){
dict = [qtext objectAtIndex:[indexPath row]];
celltext = [NSString stringWithFormat:#"%#\n\n\n",[[dict allKeys] objectAtIndex:0]];
dict = [qtype objectAtIndex:[indexPath row]];
type = [[dict allKeys] objectAtIndex:0];
//place the question
cell.textLabel.text = celltext;
// NSLog(#"row=%#",[indexpath row]);
if([type isEqualToString:#"devider"]){
[self configureDevider];
}else{
[self configureCell];
}
if([cell_id intValue] == ([qid count])){
tabledone = #"Yes";
}
tableView.backgroundColor=[UIColor clearColor];
tableView.opaque=NO;
tableView.backgroundView=nil;
NSString *a = [arrAllheight objectAtIndex:[indexPath row]];
// NSLog(#"allheight=%d",allheight);
allheight +=thisheight;
thisheight =[a intValue];
if(![tabledone isEqualToString:#"Yes"])
if([type isEqualToString:#"YN"]){
DCRoundSwitch *ynSwitch = [[DCRoundSwitch alloc] initWithFrame:CGRectMake(220,thisheight-40,80,27)] ;
ynSwitch.onText=#"Yes";
ynSwitch.offText=#"No";
[answers addObject:ynSwitch];
[cell addSubview:ynSwitch];
[ynSwitch setTag:[cell_id intValue]];
[ynSwitch addTarget:self action:#selector(setAnswersForRoundSwitches:) forControlEvents:UIControlEventValueChanged];
NSLog(#"cell_id=%#", [dicAnswers objectForKey:[NSString stringWithFormat:#"", cell_id]]);
// if[dicAnswers objectForKey:[NSString stringWithFormat:#"", cell_id]]){}
i++;
}else if([type isEqualToString:#"freetext"]){
//When the done button was clicked, remove the keybords from the screen
[self makeTextField];
[rtxtfield addTarget:self action:#selector(setAnswersfortextFields:) forControlEvents:UIControlEventEditingDidEndOnExit];
// [rtxtfield value];
}else if([type isEqualToString:#"dropdown"]){
picc = [picker_array objectForKey:[[NSString alloc] initWithFormat:#"%d",cell_id]];
//Choose an array for this textField
// [self getPickerArray];
[self makeTextField];
//[rtxtfield addTarget:self action:#selector(setAnswersfortextFields:) forControlEvents:UIControlEventEditingDidEndOnExit];
//When the done button was clicked, remove the keybords from the screen
[rtxtfield addTarget:self action:#selector(textFieldReturn:) forControlEvents:UIControlEventEditingDidEndOnExit];
//Get the tag for picker
[rtxtfield addTarget:self action:#selector(getTag:) forControlEvents:UIControlEventTouchDown];
//Display picker
[rtxtfield addTarget:self action:#selector(acsheet:) forControlEvents:UIControlEventTouchDown];
//set Tag for the textField
[rtxtfield setTag:[cell_id intValue]];
NSLog(#"rtxtfield tag=%d",rtxtfield.tag);
}
if([type isEqualToString:#"devider"]){
[self caliculateHeightofCell];
}else{
[self caliculateHeightofCell];
}
return cell;
}
get tag name when user finished editing:
-(void)getTag:(UITextField*)txtf{
NSLog(#"-------------getTag-------------");
whichTextTag = txtf.tag;
picc = [picker_array objectForKey:[[NSString alloc] initWithFormat:#"%d",whichTextTag]];
[self getPickerArray];
}
lifecycle:
- (void)viewDidLoad
{
self.view.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:#"main_bg.png"]];
// [super viewDidLoad];
dicAnswers = [NSMutableDictionary dictionary];
[self getClaimQuestions];
[self getSchemeLimitThreshold];
[self getShchemeLimit];
tabledone=#"";
[self getQuestionsAY];
// [self getQuestionsH];
[self getCountries];
// [self getQuestions];
[self getITClass];
self->table.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
self->table.separatorColor = [UIColor lightGrayColor];
[self placeNextButton];
// tabledone =#"Yes";
}
Are you using interface builder? Then check if you have not connected the tableview to the controller twice in IB - once as the view outlet and again as table.
I haven't tested your code as I don't have your data nor do I see how it's being built but looking through your code I see several problems. The most dire one though is you may not understand how dequeueReusableCellWithIdentifier is supposed to work. You appear to be defining the variable cell outside of your tableView:cellForRowAtIndexPath: which means that you could be overwriting that cell every time. I'd suggest you read up on how the dequeueReusableCellWithIdentifier is supposed to work. Have a look here: iPhone - What are reuseIdentifiers (UITableViewCell)?.

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

Checkbox selecting other checkboxes when one is selected

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!