您可以在其他类(具有数据源的类)中创建弱属性来保存对视图控制器的引用:
@property (nonatomic, weak) MyViewController *viewController;
当您添加/删除行时,只需在视图控制器上调用适当的方法,如下所示:
//行删除
[self.viewController deleteRowAtIndexPath:indexPath];
当然,您必须将此方法添加到您的视图控制器中。
您要做的最后一步是将视图控制器与您的其他类连接起来。
在您设置表视图委托的同一位置的视图控制器中,执行以下操作:
tableView.delegate = otherClass; //<- this is the class you store table view delegate.
otherClass.viewController = self;
请注意,这只是您可以执行此操作的一种方式,另一种可以是委托(如上所述)或块、通知等。
// 扩展
使用块你必须这样做。
在其他类.h:
// create typedef to avoid typing all block definition
typedef void (^CompleteBlock) (NSIndexPath *indexPath);
//Declare property
@property (nonatomic, copy) CompleteBlock removeRowCompleteBlock;
// in .m file call block where you remove row:
if (self. removeRowCompleteBlock)
self. removeRowCompleteBlock(indexPath);
在创建其他类的实例后在视图控制器文件中添加删除行块:
tableView.delegate = otherClass; //<- this is the class you store table view delegate.
otherClass.removeRowCompleteBlock = ^(NSIndexPath *indexPath) {
// od something
NSLog(@"Row removed: %@", indexPath);
};