Return NSString from UIViewController

2019-02-21 02:11发布

I want to return a NSString * from a UIViewController, called InputUIViewController, to the previous UIViewController, called CallerUIViewController, which started InputUIViewController. I want to do it just before or when InputUIViewController calls:

[self dismissModelViewControllerAnimated:YES];

Is there a standard way to do this?

2条回答
爷、活的狠高调
2楼-- · 2019-02-21 02:49

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

查看更多
该账号已被封号
3楼-- · 2019-02-21 03:06

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];
}
查看更多
登录 后发表回答