2017-02-13 81 views
1

之间传递的价值观,我有两个UIViewControllers:TimerViewControllerEfficiencyViewController(为简单起见,我们会打电话给他们TVC和EVC)初始化和ViewControllers

我试图通过某些值(2个NSString对象, 1 NSTimeInterval),当按下按钮时,从TVC到EVC。 EVC需要初始化并在按下按钮时弹出。总体而言,我尝试了两种方法。

1.直接传递值(在TVC)

 UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil]; 
EfficiencyViewController *efficiencyViewController = [storyboard instantiateViewControllerWithIdentifier:@"EfficiencyView"]; 
efficiencyViewController.category = _categoryLabel.text; 
efficiencyViewController.desc = _descriptionTextField.text; 
efficiencyViewController.duration = [_timer getInterval]; 
efficiencyViewController.modalTransitionStyle = UIModalTransitionStyleCoverVertical; 
[self presentViewController:efficiencyViewController animated:YES completion:NULL]; 

问题:当我实例EVC,我在TVC保持的值被复位,所以基本上没有数据被传递。 (我想这是因为EVC实际上是在屏幕上弹出)

2.构建一个自定义的init方法

TVC

EfficiencyViewController *efficiencyViewController = [[EfficiencyViewController alloc] initWithName:_categoryLabel.text desc:_descriptionTextField.text duration:[_timer getInterval]]; 
[self presentViewController:efficiencyViewController animated:YES completion:NULL]; 

EVC initWithName方法实现

- (id)initWithName:(NSString *)category desc:(NSString *)theDesc duration:(NSTimeInterval)theDuration { 
// self = [super initWithNibName:@"EfficiencyViewController" bundle:nil]; 
if (self != nil) { 
    _category = category; 
    _desc = theDesc; 
    _duration = theDuration; 
} 
return self; 
} 

问题:这些值根本没有被传递。而且这样,EVC缺少一些主要组件,例如按钮和文本标签。

+0

我不确定[视图控制器之间传递数据](http://stackoverflow.com/q/5210535/643383)完全重复,但它应该有所帮助。你的问题的一半似乎源于你自己实例化视图控制器。当然可以,但是你在上游游泳。 @ NRitH建议使用segues是首选路线。 – Caleb

回答

1

如果在故事板有这些,你应该用故事板SEGUE,并在TVC的prepareForSegue(),你得到的目的地视图控制器(即EVC)来自segue对象,这就是您设置EVC属性的位置。

0
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" 
bundle:nil]; EfficiencyViewController *efficiencyViewController = 
[storyboard 
instantiateViewControllerWithIdentifier:@"EfficiencyView"]; 
efficiencyViewController.category = _categoryLabel.text; 
efficiencyViewController.desc = _descriptionTextField.text; 
efficiencyViewController.duration = [_timer getInterval]; 
efficiencyViewController.modalTransitionStyle = 
UIModalTransitionStyleCoverVertical; 

使用自我代替_,看到这个链接https://stackoverflow.com/a/30901681/4912468

+0

嗯..我明白了。我选择使用_的原因是因为可读性。不会使用自我。阻碍你的代码的可读性?你怎么看? – besnuj