table view cell deleting not working
I've used the sdk standard code for deleting however it crashes once I press the delete button. I am using this code
- (void)tableView:(UITab开发者_如何转开发leView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
// Delete the row from the data source
[tableView deleteRowsAtIndexPaths:[tableFavoritesData arrayWithObject:indexPath] withRowAnimation:YES];
}
}
I tried with both NSMutableArray instead of tableFavoritesData however nothing works.
Well, basically what you want to do is:
- Delete the row from the data source (array).
- Tell the table view that you have deleted a row from the data source.
Correct code should probably look like that:
if (editingStyle == UITableViewCellEditingStyleDelete) {
[tableFavoritesData removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
EDIT: I didn't notice another error.
You need to specify the type of animation, not just pass YES or NO. For example: UITableViewRowAnimationFade. Check out possible UITableViewRowAnimation values here.
EDIT 2: For the comment below (comment formatting suck): Check out NSNotificationCenter in the docs, especially addObserver:selector:name:object: and postNotificationName:object: methods.
In your other view controller (probably viewDidLoad method):
[[NSNotificationServer defaultCenter] addObserver:self selector:@selector(deletedRow:) name:@"RowDeleted" object:nil];
-(void) deletedRow:(NSNotification*) notification
{
NSDictionary* userInfo = [notification userInfo];
NSIndexPath indexPath = [userInfo objectForKey:@"IndexPath"];
// your code here
}
and while deleting the row:
if (editingStyle == UITableViewCellEditingStyleDelete) {
...
[[NSNotificationServer defaultCenter] postNotificationName:@"RowDeleted" object:self userInfo:[NSDictionary dictionaryWithObject:indexPath forKey:@"IndexPath"]];
}
Just remember that you need to remove observer from notification center when you dealloc the other UIViewController:
[[NSNotificationServer defaultCenter] removeObserver: self];
Hope I didn't make much errors, I don't have access to XCode atm.
If you looked at the console, it will most probably tell you that your model (your data structure) doesn't match what the table expects. I.e. your delegate method
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
must return one less than before.
Also, [tableFavoritesData arrayWithObject:indexPath]
looks very strange and is probably not what's expected. Maybe you want [NSArray arrayWithObject:indexPath]
here. And remove the data from your model first.
精彩评论