我有一个NavigationController,它提供了一个视图(ShoppingController),其中包含一个我称之为ModalViewController的按钮:
AddProductController *maView = [[AddProductController alloc] init];
maView.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentModalViewController:maView animated:YES];
当我想要从我的模态视图到他父母的交换数据时,我有一个错误,因为[self parentViewController]引用我的NavigationController而不是我的ShoppingController。
如何从我的ModalView AddProductController向我的调用者ShoppingController发送数据?
答案 0 :(得分:1)
您可以使用委托模式。
在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)]
。