如何在另一个视图控制器中侦听didSelectRowAtIndexPath更改

我想监听/检测didSelectRowAtIndexPath:viewController1更改,然后基于此select更改viewController2东西。

任何想法我怎么可能去做这个?

使用KVO。

首先在ViewController1.h中创build一个@property:

 @property (strong, nonatomic) NSIndexPath *selectedIndexPath; 

在ViewController1.m中:

 @synthesize selectedIndexPath; - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { if(indexPath!=self.selectedIndexPath) self.selectedIndexPath = indexPath; //this will fire the property changed notification 

在ViewController2.m中,假设您已经对ViewController1(即vc1)进行了引用,请在您的viewDidLoad中设置Observer:

 -(void)viewDidLoad { [super viewDidLoad]; [vc1 addObserver:self forKeyPath:@"selectedIndexPath" options:NSKeyValueObservingOptionNew context:NULL]; //other stuff 

最后在ViewController2的某个地方join

 -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { //inspect 'change' dictionary, fill your boots ... } 

ETA:

您还必须删除ViewController2的dealloc中的观察者:

 -(void)dealloc { [vc1 removeObserver:self forKeyPath:@"selectedIndexPath"]; ... }