UILabel under a custom tableview cell is not getting updated - ios

My tableview cell is not getting updated on viewDidAppear :
-(void)viewDidAppear:(BOOL)animated
{
[[ApiAccess getSharedInstance] setDelegate:self];
[[[SocektAccess getSharedInstance]getSocket]setDelegate:self];
[[[SocektAccess getSharedInstance]getSocket] reconnect];
_chatSocket =[[SocektAccess getSharedInstance]getSocket];
if(self.updateWill)
{
NSLog(#"viewDidAppear");
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.updateId inSection:0];
NSLog(#"Update Value: %d",self.updateValue);
NSLog(#"Update ID: %d",self.updateId);
TimelineTableViewCell *cell = (TimelineTableViewCell *)[self.tableData cellForRowAtIndexPath:indexPath];
WallPost *data = self.myObject[indexPath.row];
data.commentCount = self.updateValue;
[self.myObject replaceObjectAtIndex:indexPath.row withObject:data];
WallPost *data2 = self.myObject[indexPath.row];
NSLog(#": %d",data2.commentCount);
cell.commentLabel.text = #" ";
[self.tableData beginUpdates];
[self.tableData reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationNone];
[self.tableData reloadData];
[self.tableData endUpdates];
}
self.updateWill = NO;
}
The self.updateWill is a boolean and has been triggered from another class :
if(self.responseAdd.responseStat.status)
{
self.commentTxt.text=#"";
[self getData];
TimelineViewController *t = (TimelineViewController *)self.navigationController.viewControllers[0];
t.updateWill = YES;
t.updateId = self.index;
t.updateValue =(int)self.response.responseData.count+1;
NSLog(#"response %d",(int)self.response.responseData.count);
}
as you can see i have created a object of my Main class which is TimelineViewController and has added the value of updateWill and other needed properties. But the cell is not getting reloaded!! whats i am doing wrong in here ??
update
(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
TimelineTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
self.counter = 0;
WallPost *data = self.myObject[indexPath.row];
cell.image.userInteractionEnabled = YES;
cell.image.tag = indexPath.row;
if(self.updateWill == YES)
{
NSLog(#"YES YES");
data.commentCount= (int)self.updateValue;
[self.tableData beginUpdates];
[self.tableData reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationNone];
[self.tableData reloadData];
[self.tableData endUpdates];
cell.commentLabel.text = [NSString stringWithFormat:#"%d comments",data.commentCount];
}
else
{
data.commentCount = (int)data.comments.count;
cell.commentLabel.text = [NSString stringWithFormat:#"%d comments",data.commentCount];
}

This is what you need to workaround in objective c
-(void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
[self.tableData reloadData];
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
//Background Thread
dispatch_async(dispatch_get_main_queue(), ^(void){
//Run UI Updates
NSArray *paths = [self.tableData indexPathsForVisibleRows];
for (NSIndexPath *path in paths)
{
//get desired cell here
CustomCell *cell = (CustomCell *)[(UITableView *)self.view cellForRowAtIndexPath: path
];
cell.labeView //now you can update here on your cell items
}
});
});
}
and this is my original logic in Swift
override func viewDidAppear(animated: Bool)
{
super.viewDidAppear(animated)
tableView.reloadData()
dispatch_async(dispatch_get_main_queue(), { () -> Void in
//get visible cells indexpaths
if let indices = self.tableView.indexPathsForVisibleRows
{
for index in indices
{
if index.section == 0 //this is specific to me, checking if section 0 is visible
{
//get desired cell here
let cell = self.tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 0,inSection: 0)) as! CustomCell
cell.myImageView.userInteractionEnabled = true //now i can update imageview on table cell
}
}
}
})
}

In viewDidLoad
[self.tableData reloadData];
I hope it will be useful.

Related

Error within tableview when cells are switching sections

So in my table view, I have an array called dataArray and it's getting its objects from a server using JSON. I added a button to each cell and when the button is clicked the cell is supposed to move to another section/ or another array called followedArray to be more exact. Now the cells are transferring to the other section but after moving 6 cells I get an error that saids this. All arrays are NSMutableArray. Also, I'm new to iOS so try to work with me, thank you.
2016-10-26 17:27:19.569 CustomCellApp[3212:198103] * Terminating app due to uncaught exception 'NSRangeException', reason: '* -[__NSArrayM objectAtIndex:]: index 6 beyond bounds [0 .. 4]'
---------------------
Side note, I can make a separate error post but I have another issue, the images displaying in the cells are being changed to other images when switching sections, using the pod SDWebImage.
---------------------
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (!isFiltered) {
if (section == 0) {
return [followedArray count];
}
else if (section == 1) {
return [dataArray count];
}
}
return [filteredArray count];
}
---------------------
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
if (section == 0) {
return #"Followed Data";
}
else {
return #"All Data";
}
}
---------------------
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// Configuring the cell
Data * dataObject;
if (!isFiltered) {
if (indexPath.section == 0) {
dataObject = [followedArray objectAtIndex:indexPath.row];
}
else if (indexPath.section == 1) {
dataObject = [dataArray objectAtIndex:indexPath.row];
}
}
else {
dataObject = [filteredArray objectAtIndex:indexPath.row];
}
// Loading Images
if (!isFiltered) {
// Exception Breakpoint Here
NSURL * imgURL = [[dataArray objectAtIndex:indexPath.row] valueForKey:#"dataURL"];
[cell.myImageView setContentMode:UIViewContentModeScaleAspectFit];
[cell.myImageView sd_setImageWithURL:imgURL placeholderImage:[UIImage imageNamed:#"no-image.png"] options:SDWebImageRefreshCached];
}else{
NSURL * imgURL = [[filteredArray objectAtIndex:indexPath.row] valueForKey:#"dataURL"];
[cell.myImageView setContentMode:UIViewContentModeScaleAspectFit];
[cell.myImageView sd_setImageWithURL:imgURL placeholderImage:[UIImage imageNamed:#"no-image.png"] options:SDWebImageRefreshCached];
}
// Loading Follow Button
cell.followButton.tag = indexPath.row;
[cell.followButton addTarget:self action:#selector(followButtonClick:) forControlEvents:UIControlEventTouchUpInside];
cell.followButton.hidden = NO;
return cell;
}
---------------------
-(void)followButtonClick:(UIButton *)sender {
// Adding row to tag
CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:self.myTableView];
NSIndexPath *indexPath = [self.myTableView indexPathForRowAtPoint:buttonPosition];
// Creating an action per tag
if (indexPath != nil)
{
// Change Follow to Following
[sender setImage:[UIImage imageNamed:#"follow.png"] forState:UIControlStateNormal];
cell.followButton.hidden = YES;
cell.followedButton.hidden = NO;
// ----- ERROR BEGINS HERE ----- //
[self.myTableView beginUpdates];
// ----- Inserting Cell to Section 0 ----- *CAUSING PROBLEMS*
// Exception Breakpoint Here
[followedArray addObject:[dataArray objectAtIndex:indexPath.row]];
[myTableView insertRowsAtIndexPaths:#[[NSIndexPath indexPathForRow:followedArray.count-1 inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
NSLog(#"indexPath.row = %ld", (long)indexPath.row);
// ----- Removing Cell from Section 1 ----- *WORKING*
[dataArray removeObjectAtIndex:indexPath.row];
NSInteger rowToRemove = indexPath.row;
[self.myTableView deleteRowsAtIndexPaths:[NSMutableArray arrayWithObjects:[NSIndexPath indexPathForRow:rowToRemove inSection:1], nil] withRowAnimation:YES];
NSLog(#"Array =%#",followedArray);
[self.myTableView endUpdates];
// ----- ERROR ENDS HERE ----- //
}
}
---------------------
This is what helped me fix the errors I was having. Credits to #AliOmari for helping me out.
In cellForRowAtIndexPath
// Configuring the cell
Data * dataObject;
if (!isFiltered) {
if (indexPath.section == 0) {
dataObject = [followedArray objectAtIndex:indexPath.row];
[cell populateCell:dataObject isFollowed:YES indexPath:indexPath parentView:self];
}
else if (indexPath.section == 1) {
dataObject = [dataArray objectAtIndex:indexPath.row];
[cell populateCell:dataObject isFollowed:NO indexPath:indexPath parentView:self];
}
}
else {
dataObject = [filteredArray objectAtIndex:indexPath.row];
[cell populateCell:dataObject isFollowed:NO indexPath:indexPath parentView:self];
}
return cell;
Inside my Button
[self.myTableView beginUpdates];
// ----- Inserting Cell to Section 0 -----
[followedArray insertObject:[dataArray objectAtIndex:indexPath.row] atIndex:0];
[myTableView insertRowsAtIndexPaths:#[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
//NSLog(#"indexPath.row = %ld", (long)indexPath.row);
// ----- Removing Cell from Section 1 -----
[dataArray removeObjectAtIndex:indexPath.row];
NSInteger rowToRemove = indexPath.row;
[self.myTableView deleteRowsAtIndexPaths:[NSMutableArray arrayWithObjects:[NSIndexPath indexPathForRow:rowToRemove inSection:1], nil] withRowAnimation:YES];
//NSLog(#"Array =%#",followedArray);
[self.myTableView endUpdates];

UILabel text is not getting changed which is in another class

I have two class
Timeline
Comment
in the Timeline class under every CustomTableViewCell represents a post and there is a option to comment on the post. To comment user has to visit the comment page which is comment class. When the user comments on it i wanted to pass that total comments count to Timeline page where it will display the comment numbers in the cell's comment label
So in my Comment class i did this when the comment is successfully posted:
TimelineViewController *t = (TimelineViewController *)self.navigationController.viewControllers[0];
t.updateWill = YES;
t.updateId = self.index;
t.updateValue =(int)self.response.responseData.count+1;
and in my Timeline class under cellForRowAtIndexPath i tried this:
if(self.updateWill == YES)
{
NSLog(#"YES YES");
data.commentCount= self.updateValue;
}
else
{
data.commentCount = (int)data.comments.count;
}
cell.commentLabel.text = [NSString stringWithFormat:#"%d comments",data.commentCount];
NSLog(#"YES YES") indicates that the logic worked. Beside if i print the self.updatevalue it also shows me the correct result but the label remain as unchanged. What i am doing wrong ??
Update:
on Timeline class at viewDidAppear
(void)viewDidAppear:(BOOL)animated
{
[[ApiAccess getSharedInstance] setDelegate:self];
[[[SocektAccess getSharedInstance]getSocket]setDelegate:self];
[[[SocektAccess getSharedInstance]getSocket] reconnect];
_chatSocket =[[SocektAccess getSharedInstance]getSocket];
if(self.updateWill)
{
NSLog(#"viewDidAppear");
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.updateId inSection:0];
NSLog(#"Update Value: %d",self.updateValue);
NSLog(#"Update ID: %d",self.updateId);
TimelineTableViewCell *cell = (TimelineTableViewCell *)[self.tableData cellForRowAtIndexPath:indexPath];
WallPost *data = self.myObject[indexPath.row];
data.commentCount = self.updateValue;
[self.myObject replaceObjectAtIndex:indexPath.row withObject:data];
WallPost *data2 = self.myObject[indexPath.row];
NSLog(#": %d",data2.commentCount);
[self.tableData reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationNone];
[self.tableData reloadData];
}
self.updateWill = NO;
}
And cellForRowAtIndexPath in Timeline class:
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
TimelineTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
self.counter = 0;
WallPost *data = self.myObject[indexPath.row];
cell.image.userInteractionEnabled = YES;
cell.image.tag = indexPath.row;
if(self.updateWill == YES)
{
NSLog(#"YES YES");
NSLog(#"Updated value : %d", (int)self.updateValue);
data.commentCount= (int)self.updateValue;
}
else
{
data.commentCount = (int)data.comments.count;
}

Remove Rows From UITableView from Previous Selected Section

Currently I have a UITableView which is expands and collapses with the current code.
- (BOOL)tableView:(UITableView *)tableView canCollapseSection:(NSInteger)section{
if (section>=0) return YES;
return NO;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
NSInteger numberofRows = 0;
numberofRows = nameArray.count;
if (numberofRows != 0){
self.mainTableView.hidden = false;
}
return numberofRows;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
if ([self tableView:tableView canCollapseSection:indexPath.section])
{
if (!indexPath.row)
{
// only first row toggles exapand/collapse
[tableView deselectRowAtIndexPath:indexPath animated:YES];
NSInteger section = indexPath.section;
BOOL currentlyExpanded = [expandedSections containsIndex:section];
NSInteger rows;
NSMutableArray *tmpArray = [NSMutableArray array];
if (currentlyExpanded)
{
rows = [self tableView:tableView numberOfRowsInSection:section];
[expandedSections removeIndex:section];
}
else
{
[expandedSections addIndex:section];
rows = [self tableView:tableView numberOfRowsInSection:section];
}
for (int i=1; i<rows; i++)
{
NSIndexPath *tmpIndexPath = [NSIndexPath indexPathForRow:i
inSection:section];
[tmpArray addObject:tmpIndexPath];
}
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
if (currentlyExpanded)
{
[tableView deleteRowsAtIndexPaths:tmpArray
withRowAnimation:UITableViewRowAnimationTop];
cell.accessoryView = [ALCustomColoredAccessory accessoryWithColor:[UIColor grayColor] type:ALCustomColoredAccessoryTypeDown];
}
else
{
[tableView insertRowsAtIndexPaths:tmpArray
withRowAnimation:UITableViewRowAnimationTop];
cell.accessoryView = [ALCustomColoredAccessory accessoryWithColor:[UIColor grayColor] type:ALCustomColoredAccessoryTypeUp];
}
}
else {
NSLog(#"Selected Section is %ld and subrow is %ld ",(long)indexPath.section ,(long)indexPath.row);
}
}
}
This works really well and upon selection of a UITableViews section the rows are expanded and populated with the correct data and when the same section is selected the rows are removed and appear collapsed.
However what i want to do is somehow automatically collapse the previous selected section and remove the rows within that previous section when the user selects a new indexpath.section.
I have tried storing the selected section index path to an array removing rows based on this value but I think I'm going about it the wrong way as I get assertion failures.
So my question is as follows :-
How can i automatically collapse (remove rows) from a uitableviews section upon selection of another section
Thanks for your help in advance
Thomas
i have faced this issue when i was writting code for my app and i founded this post that had no any single comment or answer...
You can use this code that i was written for me to colapse previous expanded rows of section when i clicked on other section and expand rows of that section, this code working for me try it...
`
- (BOOL)tableView:(UITableView *)tableView canCollapseSection:(NSInteger)section
{
if (section>=0) return YES;
return NO;
}
static NSInteger Value=0;
static NSInteger Value2=0;
static CFIndex indexPre=0;
static NSMutableArray *preArray;
static NSIndexPath *path;
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([self tableView:tableView canCollapseSection:indexPath.section])
{
if (!indexPath.row)
{
TableViewCell *cell = (TableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
cell.hideButton.hidden=NO;
[tableView deselectRowAtIndexPath:indexPath animated:YES];
NSUInteger index=[expandedSections firstIndex];
if ([expandedSections indexGreaterThanIndex:index])
{
NSLog(#"%lu hhhwww", index);
}
NSInteger section = indexPath.section;
static NSInteger rows;
static NSInteger PreRows;
NSLog(#"%lu MY INDEXES1",(unsigned long)[expandedSections count]);
NSMutableArray *tmpArray = [NSMutableArray array];
preArray = [NSMutableArray array];
BOOL currentlyExpanded = [expandedSections containsIndex:section];
if (currentlyExpanded)
{
rows = [self tableView:tableView numberOfRowsInSection:section];
[expandedSections removeIndex:section];
Value=0;
Value2=0;
cell.hideButton.hidden=YES;
}
else
{
if (Value==0)
{
[expandedSections addIndex:section];
rows = [self tableView:tableView numberOfRowsInSection:section];
PreRows = [self tableView:tableView numberOfRowsInSection:section];
indexPre=indexPath.section;
Value=1;
}
else if (Value==1)
{
Value2=1;
NSLog(#"indexPre == %ld %# my indexxxxx", indexPre, expandedSections);
[expandedSections removeIndex:indexPre];
NSLog(#"indexPre == %ld %# my indexxxxx", indexPre, expandedSections);
[self.tableView reloadData];
[expandedSections addIndex:section];
NSLog(#"indexPre == %ld %# my indexxxxx", indexPre, expandedSections);
rows=[self tableView:tableView numberOfRowsInSection:section];
}
}
NSLog(#"%# MY INDEXES",expandedSections);
if (Value2==1)
{
for (int i=1; i<PreRows; i++)
{
NSIndexPath *tmpIndexPath = [NSIndexPath indexPathForRow:i
inSection:indexPre];
[preArray addObject:tmpIndexPath];
}
NSLog(#"my arrray %#", preArray);
for (int i=1; i<rows; i++)
{
NSIndexPath *tmpIndexPath = [NSIndexPath indexPathForRow:i
inSection:section];
[tmpArray addObject:tmpIndexPath];
}
NSLog(#"my arrray tmparray%#", preArray);
}
else
{
for (int i=1; i<rows; i++)
{
NSIndexPath *tmpIndexPath = [NSIndexPath indexPathForRow:i
inSection:section];
[tmpArray addObject:tmpIndexPath];
}
}
if (currentlyExpanded )
{
[tableView deleteRowsAtIndexPaths:tmpArray
withRowAnimation:NO];
cell.accessoryView = [DTCustomColoredAccessory accessoryWithColor:[UIColor grayColor] type:DTCustomColoredAccessoryTypeDown];
}
else if(Value==1)
{
if (Value2==1)
{
[tableView beginUpdates];
[tableView insertRowsAtIndexPaths:tmpArray
withRowAnimation:NO];
cell.accessoryView = [DTCustomColoredAccessory accessoryWithColor:[UIColor grayColor] type:DTCustomColoredAccessoryTypeUp];
[tableView endUpdates];
[tableView beginUpdates];
[tableView endUpdates];
indexPre=indexPath.section;
}
else
{
[tableView insertRowsAtIndexPaths:tmpArray
withRowAnimation:UITableViewRowAnimationTop];
cell.accessoryView = [DTCustomColoredAccessory accessoryWithColor:[UIColor grayColor] type:DTCustomColoredAccessoryTypeUp];
}
}
}
}
}
`

How to code PrepareForSeque in UITableView that has sections and searching

I have constructed a nice TableView that contains sections, searching, and the alphabetical strip on the right.
I tested it and all seemed well until I noticed that anything after the "A"s was not working correctly. I discovered the reason - in my PrepareForSegue I was passing the object I found at the row, but not paying any attention to the sections.
I searched stack overflow and found some things like I am trying to do, but it seems they are coding in the didSelectRowAtIndexPath, no prepare for segue. And I was unable to get any of the code to work.
My first question is what is the relationship between the two methods? I am using Storyboards so I think I should stick with the segues. But then how do I find out which employee object to pass?
Any help would be greatly appreciated.
Bryan
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
employee *dtlEmployee = [_employees objectAtIndex:indexPath.row];
self.detailViewController.detailItem = dtlEmployee;
}
else
{
// employee *dtlEmployee;
//
// int row = indexPath.row;
// int section = indexPath.section;
//
// NSIndexPath *newIndexPath = [NSIndexPath indexPathForRow:row inSection:section];
//
// [self.tableView deselectRowAtIndexPath:newIndexPath animated:NO];
// UITableViewCell *cell = [tableView cellForRowAtIndexPath:newIndexPath];
//
// dtlEmployee = [_employees objectAtIndex:newIndexPath];
}
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:#"showDetail"]) {
employee *dtlEmployee;
// int row = [[self.tableView] indexPath.row];
// int section = [self.tableView indexPath.section];
// NSIndexPath *newIndexPath = [NSIndexPath indexPathForRow:row inSection:section];
// dtlEmployee = [_employees objectAtIndex:newIndexPath];
// NSIndexPath *selectedRowIndexPath = [self.tableView indexPathForSelectedRow];
// NSUInteger selectedRow = selectedRowIndexPath.row;
// NSUInteger selectedSection = selectedRowIndexPath.section;
// NSArray *tmpArray = [_employees objectAtIndex:[self.tableView indexPathForSelectedRow]];
// dtlEmployee = [tmpArray objectAtIndex:selectedRowIndexPath.row];
// dtlEmployee = [tmpArray objectAtIndex:indexPath.row];
//
// dtlEmployee = [_employees objectAtIndex:selectedRowIndexPath.]
//
if (isSearching)
{
dtlEmployee = [self.filteredEmployees objectAtIndex:self.searchDisplayController.searchResultsTableView.indexPathForSelectedRow.row];
}
else
{
dtlEmployee = [_employees objectAtIndex:[self.tableView indexPathForSelectedRow].row];
}
[[segue destinationViewController] setDetailItem:dtlEmployee];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [self.tableView dequeueReusableCellWithIdentifier: CellIdentifier];
//cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
if (isSearching)
{employee *thisEmployee = [self.filteredEmployees objectAtIndex:indexPath.row];
cell.textLabel.text = thisEmployee.fullName;}
else
{employee *thisEmployee = [[self.sections valueForKey:[[[self.sections allKeys] sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)] objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row];
cell.textLabel.text = thisEmployee.fullName;}
return cell;
}
Assuming that your segue is connected to the table view cell, your sender in prepareForSegue: is actually a cell. (Use logging or the debugger to be sure.)
That means you can ask your table view for an index path that matches the cell and use the same logic that you would have in tableView:cellForRowAtIndexPath: for obtaining an object from a path.
Your logic for getting the right employee in tableView:cellForRowAtIndexPath: looks like this:
if (isSearching)
{
employee *thisEmployee = [self.filteredEmployees objectAtIndex:indexPath.row];
cell.textLabel.text = thisEmployee.fullName;
}
else
{
employee *thisEmployee = [[self.sections valueForKey:[[[self.sections allKeys] sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)] objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row];
cell.textLabel.text = thisEmployee.fullName;
}
But your logic in prepareForSegue:sender: looks like this:
if (isSearching)
{
dtlEmployee = [self.filteredEmployees objectAtIndex:self.searchDisplayController.searchResultsTableView.indexPathForSelectedRow.row];
}
else
{
dtlEmployee = [_employees objectAtIndex:[self.tableView indexPathForSelectedRow].row];
}
You need to make the logic when performing the segue match the one when populating the cell, which from the sound of it works correctly. It appears that you're doing it correctly when isSearching is true, so when it's not true, the following line should be used:
employee *thisEmployee = [[self.sections valueForKey:[[[self.sections allKeys] sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)] objectAtIndex: [self.tableView indexPathForSelectedRow].section]] objectAtIndex: [self.tableView indexPathForSelectedRow].row];

Invalid TableView Update

I have 1 empty section and other sections with full of objects.I have a button in all rows.when clicked on the button in a row the row should move to the empty section.But I am getting this error saying invalid tableview update.
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid table view update. The application has requested an update to the table view that is inconsistent with the state provided by the data source.'
I tried the following Code.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
if ([[arrayForBool objectAtIndex:section] boolValue]) {
if(section == 0){
return favouritesArray.count;
}else{
NSString* key = [sectionTitleArray objectAtIndex:section - 1];
NSArray *aArray = [sectionContentDict valueForKey:key];
return aArray.count;
}
}
return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *cellIdentifier = #"UCPMenuCellIdentifier";
UCPCategoryListCell *cell = (UCPCategoryListCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell = [[[UCPCategoryListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier]autorelease];
}
if(indexPath.section == 0){
cell.textLabel.text = [favouritesArray objectAtIndex:indexPath.row ];
}
else{
NSString* key = [sectionContentDict.allKeys objectAtIndex:indexPath.section - 1];
BOOL manyCells = [[arrayForBool objectAtIndex:indexPath.section] boolValue];
if (!manyCells) {
cell.textLabel.text = #"click to enlarge";
}
else{
cell.textLabel.text = [[sectionContentDict objectForKey:key] objectAtIndex:indexPath.row];
}
}
UIButton *deletebtn=[UIButton buttonWithType:UIButtonTypeRoundedRect];
deletebtn.frame=CGRectMake(220, 10, 20, 20);
[deletebtn addTarget:self action:#selector(moveRowToFavorites:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:deletebtn];
return cell;
}
-(void)moveRowToFavorites:(id)sender{
UIButton *button = (UIButton *)sender;
UITableViewCell *cell = (UITableViewCell *)button.superview.superview;
[self.aTableView beginUpdates];
[favouritesArray addObject:cell.textLabel.text];
NSIndexPath *newindexPath = [NSIndexPath indexPathForRow:[favouritesArray count] inSection:0];
NSIndexPath *oldindexPath = [self.aTableView indexPathForCell:cell];
[self.aTableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:oldindexPath] withRowAnimation:UITableViewRowAnimationFade];
[self.aTableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newindexPath] withRowAnimation:UITableViewRowAnimationRight];
[self.aTableView endUpdates];
}
Try moveRowToFavorites: method like this:
- (void) moveRowToFavorites: (id) sender
{
UIButton* button = (UIButton*) sender;
UITableViewCell* cell = (UITableViewCell*) button.superview.superview;
[self.aTableView beginUpdates];
[favouritesArray addObject: cell.textLabel.text];
NSIndexPath* newindexPath = [NSIndexPath indexPathForRow: [favouritesArray count] - 1
inSection: 0];
[self.aTableView insertRowsAtIndexPaths: [NSArray arrayWithObject: newindexPath]
withRowAnimation: UITableViewRowAnimationRight];
NSIndexPath* oldindexPath = [self.aTableView indexPathForCell: cell];
[self.aTableView deleteRowsAtIndexPaths: [NSArray arrayWithObject: oldindexPath]
withRowAnimation: UITableViewRowAnimationFade];
NSInteger oldSection = oldindexPath.section;
NSInteger oldRow = oldindexPath.row;
NSString* key = [sectionTitleArray objectAtIndex: oldSection - 1];
NSMutableArray* anArray = [NSMutableArray arrayWithArray: [sectionContentDict valueForKey: key]];
[anArray removeObjectAtIndex: oldRow];
[sectionContentDict setValue: anArray forKey: key];
[self.aTableView endUpdates];
}
I created project with this code. It is working fine. If you need I can give.
Hope my code helps you.
In moveRowToFavorites method change arrays(favouritesArray and sectionContentDict). You have added in favouritesArray. Delete same object from other array. Then call table reloadData.
Try this. It will add to favorite section.
-(void)moveRowToFavorites:(id)sender{
UIButton *button = (UIButton *)sender;
UITableViewCell *cell = (UITableViewCell *)button.superview.superview;
[favouritesArray addObject:cell.textLabel.text];
//here you need to delete same object from [sectionContentDict objectForKey:key]
[self.aTableView reloadData];
}
Dont do anything like insertRowsAtIndexPaths or deleteRowsAtIndexPaths
In -(void)moveRowToFavorites:(id)sender after just adding object to favouritesArray, you have to remove objet from array within the sectionContentDict. And you dont have to use [table reloadData] after begin-end Updates.

Resources