views:

51

answers:

1

Hi Guys,

In my app, I want to delete particular row from table view. Table view contents are coming from database and after getting data from database then I pushed to array. Then I reversed an array, Here after I am displaying content in table view. My problem is that when I am trying to delete the second row of table view on behalf of second row it delete first row of table view. Here I put inside commitEditingStyle method code,

if (editingStyle == UITableViewCellEditingStyleDelete) {

[savedArray removeObjectAtIndex:indexPath.row];

[saveTable deleteRowsAtIndexPaths:[NSArray arrayWithObject:[savedArray objectAtIndex:val]] withRowAnimation:UITableViewRowAnimationFade];
   newsObj = [(BlackSheepAppDelegate *)[[UIApplication sharedApplication] delegate] nsManagedObjectContext];

NSFetchRequest * fetchRequest = [[NSFetchRequest alloc] init];

NSEntityDescription * entity = [NSEntityDescription entityForName:@"ArticalDetails" inManagedObjectContext:self.newsObj];

 [fetchRequest setEntity:entity];

NSError *error;

NSArray *items = [self.newsObj executeFetchRequest:fetchRequest error:&error];

[newsObj deleteObject:[items objectAtIndex:indexPath.row]];

 NSLog(@"Deleted content position %d", indexPath.row);

  if ([newsObj hasChanges] && ![newsObj save:&error]) {

  NSLog(@"%@", [error description]);
}

 [saveTable reloadData];

}

for reverse an array,

   for(int i = 0; i < [savedArray count] / 2; i++) {

  int j = [savedArray count] - i - 1;

  id temp = [[savedArray objectAtIndex:i] retain];

  [savedArray replaceObjectAtIndex:i withObject:[savedArray objectAtIndex:j]];

  [savedArray replaceObjectAtIndex:j withObject:temp];

  [temp release];

 }

Please help me out!

+1  A: 

Here is your problem:

[savedArray removeObjectAtIndex:indexPath.row];

[saveTable deleteRowsAtIndexPaths:[NSArray arrayWithObject:[savedArray objectAtIndex:val]] withRowAnimation:UITableViewRowAnimationFade];

You delete the row from the array before you remove the row from the table but you use the array itself to tell you which row of the table to delete. Whatever index val had prior to:

[savedArray removeObjectAtIndex:indexPath.row];

... will be rendered invalid by altering the savedArray itself.

This code is all needlessly complex. You don't need to manually reverse the array but should instead give the fetch request a sort descriptor so that it will return an array already sorted in whatever order you need at the moment. Better yet, you should use a NSFetchedResultsController which will handle all the complexity of adding and removing items from the table and the data for you.

TechZen