dismissModalViewControllerAnimated crashes app - iphone

I am new to iPhone development, so please pardon my ignorance.
I call a UIViewController from a UIViewController. The first UIViewController is a list of items, and the second is the detail for each of the items.
ListViewController (first UIViewController):
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// initialize a AddViewController
selItem = indexPath.row;
selIndexPath = indexPath;
AddViewController *controller = [[AddViewController alloc] init];
// give controller the data to display
// show the AddViewController
[controller setData:[list objectAtIndex:indexPath.row]];
controller.delegate = self;
[self presentModalViewController:controller animated:YES];
[controller release]; // release the controller AddViewController
} // end method tableView:didSelectRowAtIndexPath:
In the 'AddViewController' I have a segment control as both the left and right button bars. On the left, I have 'Exit' and 'Delete'. On the right I have 'Add' and 'Save'. The outlets that the segment controls are linked to are:
AddViewController (second UIViewController):
- (IBAction)delExitSegment:sender
{
// The segmented control was clicked, handle it here
UISegmentedControl *segmentedControl = (UISegmentedControl *)sender;
switch (segmentedControl.selectedSegmentIndex) {
case 0: // Exit Button
[delegate addViewControllerDidExit:self];
break;
case 1: // Delete Button
[delegate addViewControllerDelItem:self];
break;
}
}
- (IBAction)segmentAction:sender
{
// The segmented control was clicked, handle it here
UISegmentedControl *segCtl = (UISegmentedControl *)sender;
switch (segCtl.selectedSegmentIndex) {
case 0: // Add Button
if (currentCell != nil)
[data setValue:currentCell.textField.text forKey:currentCell.label.text];
[delegate addViewControllerDidFinishAdding:self];
break;
case 1: // Save Button
[delegate addViewControllerUpdate:self];
break;
}
}
When I come back to my first view controller, I have:
ListViewController:
- (void)addViewControllerDidFinishAdding:(AddViewController *)controller
{
NSDictionary *item = [controller values];
if (item != nil)
{
[list addObject:item];
}
[self dismissModalViewControllerAnimated:YES];
[list writeToFile:itemFilePath atomically:NO];
[self calcTotal];
[self.tableView reloadData];
}
- (void)addViewControllerUpdate:(AddViewController *)controller
{
NSDictionary *item = [controller values];
if (item != nil)
{
[list replaceObjectAtIndex:selItem withObject:item];
}
[self dismissModalViewControllerAnimated:YES];
[list writeToFile:itemFilePath atomically:NO];
[self calcTotal];
[self.tableView reloadData];
}
- (void)addViewControllerDidExit:(AddViewController *)controller
{
[self dismissModalViewControllerAnimated:YES];
[self.tableView reloadData];
}
- (void)addViewControllerDelItem:(AddViewController *)controller
{
NSDictionary *item = [controller values];
if (item != nil)
{
[list removeObjectAtIndex:selItem];
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:selIndexPath] withRowAnimation:UITableViewRowAnimationFade];
[list writeToFile:itemFilePath atomically:NO];
}
[self dismissModalViewControllerAnimated:YES];
[self.tableView reloadData];
}
If I exit or delete an item from AddViewController, I have no problems. When I try and add or save, then my application will crash. The debugger crashes at dismissModalViewControllerAnimated. I can't see what's different between the two segment controls.
Any ideas what I may have wrong?
I just discovered that neither the left or right buttons work when I attempt to edit a cell. The editing cell in AddViewController is as follows:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *identifier = #"EditableCell";
EditableCell *cell = (EditableCell *)[table dequeueReusableCellWithIdentifier:identifier];
if (cell == nil)
{
cell = [[EditableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
}
NSString *key = [fields objectAtIndex:indexPath.row + indexPath.section * 3];
[cell setLabelText:key];
cell.textField.text = [data valueForKey:key];
if (indexPath.section == 0 && (indexPath.row == 1 || indexPath.row == 3))
cell.textField.keyboardType = UIKeyboardTypeNumberPad;
if (indexPath.section == 1)
cell.textField.keyboardType = UIKeyboardTypeNumberPad;
cell.editing = NO;
cell.delegate = self;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
}

Here is the problem:
[self dismissModalViewControllerAnimated:YES];
[self.tableView reloadData];
When you dismiss the view the value of self become unknown, accessing the tableview will definitely crash.
If you want to refresh the tableView just use [self.tableView reloadData] and don't dismiss the view.

Related

Views are getting overlapped in ios

This is my main screen where I added a table view.Now the problem arises when I click any of the tab ,my tab bar controller views is getting overlapped by the main view controller .
I need to resolve this error.
. If you didn't get my question correctly,please let me know.
Thanks
In Appdelegate I didn't write any code.
//MainViewController.m
- (void)viewDidLoad
{
getValuesFormDatabase=[[NSMutableArray alloc]init];
[self getAllRowsFromTableNamed];
[self getRefershToken];
}
//tab bar items
- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item {
switch(item.tag){
case 1:
if (homeViewController == nil) {
self.homeViewController =
[[HomeViewController alloc] initWithNibName:homeViewController bundle:nil];
}
[self.view insertSubview:homeViewController.view belowSubview:myTabBar];
if (currentViewController != nil)
[currentViewController.view removeFromSuperview];
currentViewController = homeViewController;
break;
case 2:
if (top25ViewController == nil)
{
self.top25ViewController =
[[Top25ViewController alloc] initWithNibName:top25ViewController bundle:nil];
}
[self.view insertSubview:top25ViewController.view belowSubview:myTabBar];
[ALToastView toastInView:self.view withText:#"Server is not responding"];
if (currentViewController != nil)
[currentViewController.view removeFromSuperview];
currentViewController = top25ViewController;
break;
case 3:
if (myfavViewController == nil) {
self.myfavViewController =
[[MyFavViewController alloc] initWithNibName:myfavViewController bundle:nil];
}
[self.view insertSubview:myfavViewController.view belowSubview:myTabBar];
if (currentViewController != nil)
[currentViewController.view removeFromSuperview];
currentViewController = myfavViewController;
break;
case 4:
if (moreViewController == nil) {
self.moreViewController =
[[MoreViewController alloc] initWithNibName:moreViewController bundle:nil];
}
[self.view insertSubview:moreViewController.view belowSubview:myTabBar];
if (currentViewController != nil)
[currentViewController.view removeFromSuperview];
currentViewController = moreViewController;
break;
}
}
//table view
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [getValuesFormDatabase count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"Cell";
MainCell *cell = (MainCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell==nil) {
cell=[[MainCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
cell.mainViewChannelName.text=[TableChannelNameArray objectAtIndex:indexPath.row];
cell.mainViewVideoName.text=[TableVideoNameArray objectAtIndex:indexPath.row];
return cell;
}

How to grayout all tableview cells except selected one

I have a table view with custom cells ,there are uibuttons on custom cell ,if i select button except that cell remaining all cells should be grayouted or disabled is it possible.
// code in tableview class
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
{
NSLog(#"No OF rows:%d",[contents count]);
return [contents count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
{
static NSString *cellIdentifier = #"cell";
// Try to retrieve from the table view a now-unused cell with the given identifier.
cell = (uploadCustomCell *)[tableView dequeueReusableCellWithIdentifier:#"uploadCustomCell"];
if (cell == nil) {
NSLog(#"cell allocated");
// Use the default cell style.
cell = [[uploadCustomCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"uploadCustomCell"];
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"uploadCustomCell"
owner:self options:nil];
cell = [nib objectAtIndex:0];
}
saveBtnCcell.hidden = YES;
cell.textNamefield.hidden = YES;
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
[cell.defaultSwitch setEnabled:NO];
dictionaryContents = [contents objectAtIndex:indexPath.row];
NSLog(#"dict dict :%#",dictionaryContents);
//
cell
.nameLabelCell.text = [dictionaryContents valueForKey:#"VideoName"];
cell.userName.text = [dictionaryContents valueForKey:#"User"];
NSLog(#"Array Image:%#",arrayimage);
cell.thumbImg.image = [arrayimage objectAtIndex:indexPath.row];
NSLog(#"ARimage:%#,index%d",[arrayimage objectAtIndex:indexPath.row],indexPath.row);
NSString *defaultVideo = [dictionaryContents valueForKey:#"DefaultVideo"];
NSLog(#"Default Video:%#",defaultVideo);
if ([defaultVideo isEqual: #"1"]) {
// [cell.defaultSwitch setOn:YES animated:YES];
[defaultSwitche setOn:YES animated:YES];
}
else{
// [cell.defaultSwitch setOn:NO animated:YES];
[defaultSwitche setOn:NO animated:YES];
}
[cell.defaultSwitch addTarget:self action:#selector(setState:) forControlEvents:UIControlEventValueChanged];
VideoNameTextField.hidden = YES;
return cell;
}
// Code in customcell
#interface uploadCustomCell (){
UploadAllViewController *uploadAll;
}
#end
#implementation uploadCustomCell
#synthesize textNamefield;
#synthesize savebtn,edit,nameLabelCell,textLabel,uploadBTN;
#synthesize defaultSwitch;
//#synthesize uploadAll;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
}
return self;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
- (void)dealloc {
[_userName release];
[_thumbImg release];
//[savebtn release];
[textNamefield release];
[nameLabelCell release];
[_test release];
[savebtn release];
[defaultSwitch release];
[uploadBTN release];
[super dealloc];
}
- (IBAction)editAction:(id)sender {
[uploadBTN setEnabled:NO];
uploadAll = [[UploadAllViewController alloc]init];
CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:uploadAll.tabelView1];
NSIndexPath *indexPath = [uploadAll.tabelView1 indexPathForRowAtPoint:buttonPosition];
int no = indexPath.row;
NSLog(#"index path :%d",no);
[uploadAll didEditButtonPressed:self];
}
- (IBAction)saveBtnAction:(id)sender {
[uploadBTN setEnabled:YES];
[uploadAll didSaveButtonPressed:self];
}
when i select this editAction: except that cell remaining cells should be grayouted.
In your cellForRowAtIndexPath you have to account for the state of your table view, i.e. if one or zero cells are selected. Use that to change the appearance of your cell as you wish. In the example below I have assumed you are having a straight array without any sections, but the same principle would work with indexPaths as well. I use an int selectedRow set to -1 if there is no cell selected.
#define kNoCellSelected -1
// in cellForRowAtIndexPath:
if (self.selectedRow == kNoCellSelected) {
cell.backgroundView.backgroundColor = normalColor;
cell.userInteractionEnabled = YES;
}
else if (self.selectedRow != indexPath.row) {
cell.backgroundView.backgroundColor = disabledColor;
cell.userInteractionEnabled = NO;
}
Don't forget to set selectedRow in didSelectRowAtIndexPath: and in viewDidLoad.

Automatically load more articles in TableView

I have TableView and in this TableView I'm printing articles. Now user must click in navigation bar item to update(download more articles from web over json). I want and I think that is better that when user scroll to bottom that automaticaly shows loading cell and start to loading or getting more articles from web.
My questions are next:
How to put that extra cell in which would appear loading indicator
and loading text How to automatically get more articles?
This functionality is in iphone app "App Store" but with click load more items.
Maybe is better to put button load more articles?
All examples and suggestions are welcome.
Thank's for help
This one is easy it's add an UITablecell at the end to load more items.
//
// TableViewController.m
// PartialTable
//
// Created by Abizer Nasir on 07/07/2011.
//
#import "TableViewController.h"
#define kNumberOfItemsToAdd 8
#implementation TableViewController
#synthesize items;
// Mark: -
// Mark: Set up and tear down
- (id)init {
// New designated initialiser
if (!(self = [super initWithStyle:UITableViewStyleGrouped])) {
return nil; // Bail!
}
numberOfItemsToDisplay = kNumberOfItemsToAdd; // Show 10 items at startup
return self;
}
- (id)initWithStyle:(UITableViewStyle)style {
// Call out to the new designated initialiser
return [self init];
}
- (void)dealloc {
[items release];
[super dealloc];
}
#pragma mark - View lifecycle
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
if (numberOfItemsToDisplay == [items count]) {
return 1;
}
return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (section == 0) {
return numberOfItemsToDisplay;
} else {
return 1;
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"ItemCell";
// If the indexPath is less than the numberOfItemsToDisplay, configure and return a normal cell,
// otherwise, replace it with a button cell.
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
if (indexPath.section == 0) {
cell.textLabel.text = [items objectAtIndex:indexPath.row];
cell.textLabel.textAlignment = UITextAlignmentLeft;
cell.textLabel.textColor = [UIColor blackColor];
cell.textLabel.font = [UIFont boldSystemFontOfSize:17.f];
} else {
cell.textLabel.text = [NSString stringWithFormat:NSLocalizedString(#"Next %d items", #"The text to display to load more content"), kNumberOfItemsToAdd];
cell.textLabel.textAlignment = UITextAlignmentCenter;
cell.textLabel.textColor = [UIColor colorWithRed:0.196f green:0.3098f blue:0.52f alpha:1.f];
cell.textLabel.font = [UIFont boldSystemFontOfSize:14.f];
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if (indexPath.section == 1) {
NSUInteger i, totalNumberOfItems = [items count];
NSUInteger newNumberOfItemsToDisplay = MIN(totalNumberOfItems, numberOfItemsToDisplay + kNumberOfItemsToAdd);
NSMutableArray *indexPaths = [[NSMutableArray alloc] init];
for (i=numberOfItemsToDisplay; i<newNumberOfItemsToDisplay; i++) {
[indexPaths addObject:[NSIndexPath indexPathForRow:i inSection:0]];
}
numberOfItemsToDisplay = newNumberOfItemsToDisplay;
[tableView beginUpdates];
[tableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationTop];
[indexPaths release];
if (numberOfItemsToDisplay == totalNumberOfItems) {
[tableView deleteSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationTop];
}
[tableView endUpdates];
// Scroll the cell to the top of the table
if (newNumberOfItemsToDisplay < totalNumberOfItems) {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 200000000), dispatch_get_main_queue(), ^(void){
[tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
});
[tableView deselectRowAtIndexPath:indexPath animated:YES];
} else {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 200000000), dispatch_get_main_queue(), ^(void){
[tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:totalNumberOfItems-1 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
});
}
}
}
#end
Q1: add 1 more cell for load more status:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return cellsCount <= 0 ? 0 : cellsCount + 1;
}
and create load more cell:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.row == cellsCount) {
if (loadMoreCell == nil) {
self.loadMoreCell = [[LoadMoreTableCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:#"LoadMoreCellIdentifier"];
}
return loadMoreCell;
}
...
}
You can custom LoadMoreTableCell as you want.
Q2:
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
float offset = (scrollView.contentOffset.y - (scrollView.contentSize.height - scrollView.frame.size.height));
if (offset >= 0 && offset <= 5) {
[self loadMoreData];
}
}
I also do like this thing in my app,
Here you can use AsyncImage class which is useful to download image with url in background so your tableview scroll smooth..
here two link hope this help you for download image in background...
1.https://github.com/Koolistov/Image-Cache
2.https://github.com/rs/SDWebImage
2nd thing you want to download at bottom to another data and cell then here if you use 1 condition then its work which you like...
in cellForRowAtIndexPath tableview Delegate Method
if(indexPath.row==[yourArray count]-1){
.....do somthing which you like.....(Reload table with your json or another data)
}
here only simple logic other wise better idea is put button at your last row...
Hope this help you..
:)

Calling a New View by selecting a UITableView Row Error

I am having some issues with pulling up specific ViewControllers depending on which row is selected in my UITableView. I have a table, which contains 3 sections, with 4 rows in each section.
When a row is selected I have it set to call a new view for each row, so 12 views in total to be called depending on which row is selected. The issue is, that only the first 4 views are called, when I tap row number 5, it displays a new view, but it pulls up the first view.
I have set my UITableView up using the following code;
carbData = [[NSArray alloc] initWithObjects:#"What Are Carbs?",#"Why Do I Need Carbs?",#"Simple Vs. Complex",#"Fun Five Facts",nil];
proteinData = [[NSArray alloc] initWithObjects:#"What is Protein?",#"Why Do I Need Protein?",#"Complete Vs. Incomplete",#"Fun Five Facts",nil];
fatData = [[NSArray alloc] initWithObjects:#"What Are Fats?",#"Why Do I Need Fats?",#"Saturated Vs. Unsaturated",#"Fun Five Facts",nil];
[self setTitle:#"Nutrition Table"];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 3;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.carbData count];
return [self.proteinData count];
return [self.fatData count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *SimpleTableIdentifier = #"SimpleTableIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: SimpleTableIdentifier];
if (cell == nil) { cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:SimpleTableIdentifier] autorelease];
}
if(indexPath.section == 0)
cell.text = [carbData objectAtIndex:indexPath.row];
if(indexPath.section == 1)
cell.text = [proteinData objectAtIndex:indexPath.row];
if (indexPath.section == 2)
cell.text = [fatData objectAtIndex:indexPath.row];
return cell;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
if(section == 0)
return #"Carbohydrates";
if (section ==1)
return #"Protein";
else if (section ==2)
return #"Fats";
}
I then use the following code to determine which view is to be called, when a certain row is selected;
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if ([[carbData objectAtIndex:indexPath.row] isEqual:#"What Are Carbs?"]) {
CarbsView1 *controller = [[CarbsView1 alloc] initWithNibName:#"CarbsView1" bundle:nil];
controller.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentModalViewController:controller animated:YES];
[controller release];
}
if ([[carbData objectAtIndex:indexPath.row] isEqual:#"Why Do I Need Carbs?"]) {
CarbsView2 *controller = [[CarbsView2 alloc] initWithNibName:#"CarbsView2" bundle:nil];
controller.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentModalViewController:controller animated:YES];
[controller release];
}
if ([[carbData objectAtIndex:indexPath.row] isEqual:#"Simple Vs. Complex"]) {
CarbsView3 *controller = [[CarbsView3 alloc] initWithNibName:#"CarbsView3" bundle:nil];
controller.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentModalViewController:controller animated:YES];
[controller release];
}
if ([[carbData objectAtIndex:indexPath.row] isEqual:#"Fun Five Facts"]) {
CarbsView4 *controller = [[CarbsView4 alloc] initWithNibName:#"CarbsView4" bundle:nil];
controller.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentModalViewController:controller animated:YES];
[controller release];
}
if ([[proteinData objectAtIndex:indexPath.row] isEqual:#"What is Protein?"]) {
ProteinView1 *controller = [[CarbsView4 alloc] initWithNibName:#"ProteinView1" bundle:nil];
controller.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentModalViewController:controller animated:YES];
[controller release];
}
The app compiles and builds fine, everything works as i'd like it too, however when looking at the titles used, when I try and select "What is Protein?" is pulls up the view for "what are Carbs?" which is in the first if statement.
Any help would be massively appreciated
"What is Protein?" is in section 1, row 0. "What are Carbs?" is in section 0, row 0. Notice that your didSelectRowAtIndexPath method, you don't check the section number anywhere. So when you tap section 1, row 0, your first if statement returns true. I think you want something more like:
if (indexPath.section == 0) {
if(indexPath.row == 0) {
//present appropriate view controller
} else if (indexPath.row == 1) {
} else if (indexPath.row == 2) {
} ...
} else if (indexPath.section == 1) {
if (indexPath.row == 0) {
} else if (indexPath.row == 1) {
} ...
} ...

will lead to "Program received signal: “SIGKILL”."

I have a UITableView, where I extend/shrink the cells with the following code.
I save the last 2 indexPaths to perform a reloadRowsAtIndexPaths: on it.
Now I added a UISearchBar to the header for section 0. If I tab the searchBar, a KeyBoard is displayed on top of the UITableView — so far so good.
But I want the user to be able to touch the Cells and disable the KeyBoard. To do so, I test if the searchbox is the first responder inside the -tableView:didSelectRowAtIndexPath:
But doing so will lead to a "SIGKILL" in one of the rows marks 1, 2, 3
I really don't understand why
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
Article *article = [articles objectAtIndex:indexPath.row];
ArticleCell *cell = (ArticleCell*)[self.tableView dequeueReusableCellWithIdentifier:#"articelcell"];
if (cell == nil)
{
cell = [[[NSBundle mainBundle] loadNibNamed:#"ExtendibleCell" owner:self options:nil] objectAtIndex:0];
}
//....
cell.articleName.text = [NSString stringWithFormat:#"%#",article.name ];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
if ([searchBar isFirstResponder]) {
[searchBar resignFirstResponder];
}
[orderTableDelegate receiveSelectedArticleName:[[articles objectAtIndex:indexPath.row] name]];
firstSelected = lastSelected;
lastSelected = indexPath;
if (lastSelected == firstSelected && firstSelected != nil) {
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:lastSelected] withRowAnimation:CELL_ANIMATION]; //1
lastSelected = nil;
firstSelected = nil;
return;
}
if (lastSelected != nil) {
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:CELL_ANIMATION];//2
}
if (firstSelected != nil) {
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:firstSelected] withRowAnimation:CELL_ANIMATION];//3
}
}
-(UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
if (section ==0) {
if (searchBar == nil) {
searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
[searchBar setShowsBookmarkButton:YES];
[searchBar setKeyboardType:UIKeyboardTypeAlphabet];
[searchBar setBarStyle:UIBarStyleBlack];
[searchBar setShowsCancelButton:YES];
[searchBar setDelegate:self];
}
return searchBar;
}
return nil;
}
-(float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([indexPath isEqual:lastSelected] && lastSelected!=firstSelected) {
return [[(Article *)[articles objectAtIndex:indexPath.row] sizesAndPrices] count]*PACKAGESIZE_PRICE_BUTTON_HEIGHT +30;
}
return 40.0;
}
edit
I cleaned up my code for -tableView:didSelectRowAtIndexPath:, but the problem stays the same
#property(nonatomic,retain) NSIndexPath *firstSelected;
#property(nonatomic,retain) NSIndexPath *lastSelected;
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
[orderTableDelegate receiveSelectedArticleName:[[articles objectAtIndex:indexPath.row] name]];
self.firstSelected = nil;
self.firstSelected = self.lastSelected;
self.lastSelected = nil;
self.lastSelected = [indexPath retain];
if (self.firstSelected == self.lastSelected) {
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:self.firstSelected] withRowAnimation:CELL_ANIMATION];
[self.firstSelected release];
[self.lastSelected release];
self.firstSelected = nil ;
self.lastSelected = nil ;
} else {
if (self.firstSelected != nil) {
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:self.firstSelected] withRowAnimation:CELL_ANIMATION];
}
if (self.lastSelected != nil) {
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:self.lastSelected] withRowAnimation:CELL_ANIMATION];
}
}
if ([searchBar isFirstResponder]) {
[searchBar resignFirstResponder];
}
}
firstSelected = lastSelected;
lastSelected = indexPath;
This leads me to believe that lastSelected is an instance variable? If this is the case, you are not properly retaining it, and there is no guarantee that it is still alive beyond the scope of this method. The indexPath passed in the didSelectRowAtIndexPath: argument needs to be retained if you are going to use it after it's execution.
Keep in mind, if you do that, you need better memory management throughout that method...i.e. releasing lastSelected before changing it's value or setting it to nil.
Assuming firstSelected and lastSelected are instance variables, you could do something like this. (all the releasing and != checking would go away if you made them retained properties and used the setter)
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
if ([searchBar isFirstResponder]) {
[searchBar resignFirstResponder];
}
[orderTableDelegate receiveSelectedArticleName:[[articles objectAtIndex:indexPath.row] name]];
if (firstSelected != lastSelected) {
[firstSelected release];
firstSelected = [lastSelected retain];
}
if (lastSelected != lastSelected) {
[lastSelected release];
lastSelected = [indexPath retain];
}
if (lastSelected == firstSelected && firstSelected != nil) {
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:lastSelected] withRowAnimation:CELL_ANIMATION]; //1
[lastSelected release];
lastSelected = nil;
[firstSelected release];
firstSelected = nil;
return;
}
if (lastSelected != nil) {
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:CELL_ANIMATION];//2
}
if (firstSelected != nil) {
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:firstSelected] withRowAnimation:CELL_ANIMATION];//3
}
}