【问题标题】:Pass data in modal segue in storyboard?在情节提要中以模态序列传递数据?
【发布时间】:2015-09-02 07:23:42
【问题描述】:

我真正的问题是我想通过 modal segue 将数据从 childViewController 传递到情节提要中的 parentViewController。

代码

parentViewController.h

@property (strong, nonatomic)NSMutableArray *address;

childViewController.m

parentViewController *parent=(parentViewController *)self.presentingViewController;
post.address=@"Hello World";

这段代码抛出 exception

由于未捕获的异常而终止应用 'NSInvalidArgumentException',原因:'-[MainTabbarViewController setAddress:]: 无法识别的选择器发送到实例 0x7fa070e6b910'

故事板结构

TabbarController-> NavigationController-> parentViewController-> childViewController

在此先感谢您。

【问题讨论】:

  • @Devashi ...我认为委托是一个更好的选择....nsuserdefault...啊哈...我不这么认为....

标签: ios objective-c iphone storyboard modalviewcontroller


【解决方案1】:

您不能像这样将数据传递回父视图控制器。委派是实现这一点的最佳方式。 请查看以下链接,其中有详细说明。

passing-data-between-view-controllers

【讨论】:

  • 我认为这是很长的代码。 nsuserdefault 传数据比这个好。你说什么?
【解决方案2】:

没有办法获得对创建您的 segue 的引用。您可以在目标控制器中创建一个属性(在我的示例中为 sourceVC),并在 prepareForSegue 方法中(在源视图控制器中)将 self 分配给该属性:

[(ChildViewController *)segue.destinationViewController sourceVC] = self;

无论如何,我认为使用委托是一个更好的解决方案。

* 在 ChildViewController.h *

@protocol ChildDelegate <NSObject>
- (void)postAddress:(NSString*)ad;
@end

@interface ChildViewController : UIViewController
@property (weak, nonatomic) id <ChildDelegate> delegate;
@end

* 在 ParentViewController.h *

@interface ParentViewController : UIViewController <ChildDelegate>
@end

* 在 ParentViewController.m *

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
       ChildViewController *vc = [segue destinationViewController];
       vc.delegate = self;
}

* 在 ChildViewController.m *

- (void)changeAddress:(NSString*)ad
{
   if ([self.delegate respondsToSelector:@selector(postAddress:)])
    {
        // Tell the delegate something.
        [self.delegate postAddress:@"New Address"];
    }
}

【讨论】:

  • 我认为这是很长的代码。 nsuserdefault 传数据比这个好。你说什么?
  • 我发现这是一个非常糟糕的做法,但如何使用 NSUserDefaults 取决于您。
【解决方案3】:

正确的方法是使用委托

ChildViewController.h

@protocol ChildDelegate 
- (void)postAddress:(NSString *)address;
@end 
@interface ChildViewController
@property (nonAtomic, assign) id<ChildDelegate> delegate;
@end

ChildViewController.m

[self.delegate postAddress:address];

ParentViewController.h

@interface ParentViewController <ChildDelegate>
@end

ParentViewController.m

// presenting childViewController
- (void)presentChildViewController {   
    ChildViewController *childViewController = [[ChildViewController alloc]init];
    childViewController.delegate = self;
    [self presentViewController:childViewController animated:YES completion:nil];
}


// delegate method
- (void)postAddress:(NSString *)address{
    // add you code here
}

【讨论】:

  • 我认为这是很长的代码。 nsuserdefault 传数据比这个好。你说什么?
猜你喜欢
  • 2023-03-03
  • 2012-06-02
  • 1970-01-01
  • 2013-10-27
  • 1970-01-01
  • 2014-01-01
  • 1970-01-01
  • 2016-02-15
  • 2011-12-27
相关资源
最近更新 更多