Calling (deleteRowsAtIndexPaths) outside (commitEditingStyle) in Objective-C for iPhone

I have a custom UITableViewCellone in which two custom ones are added UIButton. On one of these buttons, I want to remove the cell row from myMethod().

The method is called addTarget:@selector(myMethod:)inside cellForRowAtIndexPath:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ...
    cell.acceptButton.tag = indexPath.row;
    [cell.contentView addSubview:acceptButton];

    [cell.acceptButton addTarget:self action:@selector(myMethod:) forControlEvents:UIControlEventTouchUpInside];
}

This works, the actual method is called successfully.

- (void)myMethod:(id)sender {
   NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow]; //works fine (correct indexPath is returned)
   friendsArray removeObjectAtIndex:indexPath.row]; //works fine (correct indexPath.row is returned and the object is removed from the array)
   [tv deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; //throws error below
}

Error:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSArray initWithObjects:count:]: attempt to insert nil object at objects[0]'
*** Call stack at first throw:
(
 0   CoreFoundation                      0x020a9be9 __exceptionPreprocess + 185
 1   libobjc.A.dylib                     0x021fe5c2 objc_exception_throw + 47
 2   CoreFoundation                      0x01ff3ffe -[__NSPlaceholderArray initWithObjects:count:] + 494
 3   CoreFoundation                      0x020158a3 +[NSArray arrayWithObject:] + 67
 4   MyApp                          0x00071d1b -[FriendListViewController myMethod:] + 417
 5   MyApp                          0x00020b87 -[MBProgressHUD launchExecution] + 151
 6   Foundation                          0x004a3d4c -[NSThread main] + 81
 7   Foundation                          0x004a3cd8 __NSThread__main__ + 1387
 8   libSystem.B.dylib                   0x9461f85d _pthread_start + 345
 9   libSystem.B.dylib                   0x9461f6e2 thread_start + 34

I usually did this when deleting a row inside a cell. This works great:

- (void)tableView:(UITableView *)tableview commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
 if(editingStyle == UITableViewCellEditingStyleDelete) {
  //Delete the object from the friends array and the table.
  [friendsArray removeObjectAtIndex:indexPath.row];
  [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
 }
}
+3
source share
2 answers

if you use uibutton for each cell or more than one cell and set the same selector than the best option is to recognize the cell using tags.

, ( , , -, ). , accessView . . tableView:cellForRowAtIndexPath:

0

, . , indexPath nil.

0

Source: https://habr.com/ru/post/1784895/


All Articles