就是在删除某行的时候为什么要先删除数据模型中的实例
例如以下例子:
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
[_items removeObjectAtIndex:indexPath.row];
//为什么要有以上代码,不要以上代码为什么不行,_items是一数组,而且放在后面这行代码的后面也不行这是为什么
NSArray *indexPaths = @[indexPath]; //还有这段代码能具体解释下吗
[tableView deleteRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationAutomatic];
}
First explain
This is an operation on the interface. It uses some animation to delete the row you want to delete. It only operates the UI and does not operate the data.
Then
This is the real operational data. Your _items should be the dataSource of tableView, right? Only when operating the UI, the data in the data source (_items) is actually deleted, in
, the data you deleted before will not be displayed again.
As for why those two lines of code must be in that order, I don’t know... I hope an expert can answer it and let’s learn from it~
If there are any mistakes in the answer, please criticize and correct me
NSArray *indexPaths = @[indexPath];
This line of code creates a new array pointer pointing to the passed subscript. Note that this is just a pointer, operations on it will affect indexPath
If you delete object in the following line, the indexPath pointed to by the pointer will also be affected, so when indexPath is called later, its value has changed. It is recommended that you output the indexPath value (or row value) in the log between these two lines of code to see if there has been any change.
You can view the above code as
The difference between the two is that the first method only deletes a certain row (Cell) without having to update the entire UITableView and causing a waste of resources. It also provides better-looking special effects; the second method is more blunt
This method alone is difficult to convince, let me take it next
As an example
Assuming we are adding a new row, if you call
insertRowsAtIndexPaths:withRowAnimation:
first,UITableView will call
tableView:cellForRowAtIndexPath:
to get the cell of the new rowYou must all write this in the code
tableView:cellForRowAtIndexPath:
Obviously because you did not add data, the access will be out of bounds
This is why when updating the UI of UITableView, the data must be updated first