我有一个NavigationController,它提供一个带有按钮的视图(ShoppingController),我称之为ModalViewController:
AddProductController *maView = [[AddProductController alloc] init];
maView.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentModalViewController:maView animated:YES];
当我想从模态视图向其父级交换数据时,出现错误,因为[self parentViewController]引用了我的NavigationController而不是我的ShoppingController。
如何将数据从ModalView AddProductController发送到调用者ShoppingController?
最佳答案
您可以使用委托模式。
在您的AddProductController类中,当处理按钮轻击时,您可以向其委托(您将其设置为ShoppingController)发送一条消息。
因此,在AddProductController中:
-(void)buttonHandler:(id)sender {
// after doing some stuff and handling the button tap, i check to see if i have a delegate.
// if i have a delegate, then check if it responds to a particular selector, and if so, call the selector and send some data
// the "someData" object is the data you want to pass to the caller/delegate
if (self.delegate && [self.delegate respondsToSelector:@selector(receiveData:)])
[self.delegate performSelector:@selector(receiveData:) withObject:someData];
}
然后,在ShoppingController中(并且不要忘记释放maView):
-(void)someMethod {
AddProductController *maView = [[AddProductController alloc] init];
maView.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
maView.delegate = self;
[self presentModalViewController:maView animated:YES];
[maView release];
}
-(void)receiveData:(id)someData {
// do something with someData passed from AddProductController
}
如果想花哨的话,可以将receiveData:作为协议的一部分。然后,您的ShoppingController可以实现该协议,而无需检查
[self.delegate respondsToSelector:@selector(x)]
,而是检查该[self.delegate conformsToProtocol:@protocol(y)]
。