Return NSString from UIViewController

后端 未结 2 1841
清歌不尽
清歌不尽 2021-01-16 16:40

I want to return a NSString * from a UIViewController, called InputUIViewController, to the previous UIViewController, called CallerUIViewController, which star

相关标签:
2条回答
  • 2021-01-16 17:11

    The standard way to do this would be to use a delegate.

    In your InputViewController add a new delegate protocal, and a property for your delegate.

    Then in your CallerUIViewController implement the delegate. Then just before your dismiss the modal view controller you can call back to your delegate.

    So your InputViewController might look like this:

    @protocol InputViewControllerDelegate;
    
    @interface InputViewControllerDelegate : UIViewController {
    }
    
    @property (nonatomic, assign) id <InputViewControllerDelegate> delegate;
    
    @end
    
    
    @protocol InputViewControllerDelegate
    - (void)didFinishWithInputView:(NSString *)stringValue;
    @end
    

    The method that dismisses the modal view would look something like this:

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

    Then in your CallerUIViewController you would implement the InputViewControllerDelegate and the didFinishWithInputView method.

    The CallerUIViewController header would look something like:

    @interface CallerUIViewController : UIViewController <InputViewControllerDelegate> {
    }
    

    and your didFinishWithInputView method would be implemented something like:

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

    Just before your present the InputViewController you would set the delegate to self.

    -(void)showInputViewController
    {
       InputViewController *inputVC = [[InputViewController alloc] init];
       inputVC.delegate = self;
    
       [self presentModalViewController:inputVC animated:YES];
    
       [inputVC release];
    }
    
    0 讨论(0)
  • 2021-01-16 17:26

    You can do this by simply creating a NSString object as property in prvious view controller and when in second view you call dismissModelViewControllerAnimated then before it assign value to previous view controller property. This might help you -

    Passing data between classes using Objective-C

    0 讨论(0)
提交回复
热议问题