2011-11-04 74 views
0

我想从一个名为InputUIViewController的UIViewController返回一个NSString *到之前称为CallerUIViewController的UIViewController,它启动了InputUIViewController。我只想做之前,或当InputUIViewController电话:从UIViewController返回NSString

[self dismissModelViewControllerAnimated:YES];

有没有做到这一点的标准方式?

+0

使用委托。 –

回答

10

标准的方式做,这是使用委托。

在你的InputViewController中为你的委托添加一个新的委托协议和一个属性。

然后在你的CallerUIViewController中实现委托。然后就在您关闭模式视图控制器之前,您可以回拨给您的代理。

所以你InputViewController可能是这样的:

@protocol InputViewControllerDelegate; 

@interface InputViewControllerDelegate : UIViewController { 
} 

@property (nonatomic, assign) id <InputViewControllerDelegate> delegate; 

@end 


@protocol InputViewControllerDelegate 
- (void)didFinishWithInputView:(NSString *)stringValue; 
@end 

是驳回模式的看法会是这个样子的方法:

-(void)dismissSelf 
{ 
    [self.delegate didFinishWithInputView:@"MY STRING VALUE"]; 
    [self dismissModalViewControllerAnimated:YES]; 
} 

然后在你的CallerUIViewController你将实现InputViewControllerDelegate和didFinishWithInputView方法。

的CallerUIViewController头看起来是这样的:

@interface CallerUIViewController : UIViewController <InputViewControllerDelegate> { 
} 

和你didFinishWithInputView方法将实施类似:

- (void)didFinishWithInputView:(NSString *)stringValue 
{ 
    // This method will be called by the InputViewController just before it is dismissed 
} 

之前就你目前的InputViewController你会委托设置为self。

-(void)showInputViewController 
{ 
    InputViewController *inputVC = [[InputViewController alloc] init]; 
    inputVC.delegate = self; 

    [self presentModalViewController:inputVC animated:YES]; 

    [inputVC release]; 
} 
+0

它可能看起来像很多代码,但这是正确的方法。它将这两个控制器分开。 –

0

您可以通过简单地创建在prvious视图控制器NSString对象property做到这一点,当第二视图可以dismissModelViewControllerAnimated然后才将值分配给一个视图控制器property。这可以帮助你 -

Passing data between classes using Objective-C