通过ViewControllers传递数据不起作用

时间:2015-01-11 21:55:22

标签: ios objective-c uiviewcontroller viewcontroller message-passing

好的,所以我试图通过以下代码将数据从一个视图控制器传递到另一个视图控制器,但它不起作用,我不明白为什么。

在我的ViewController.m中,我导入了ViewControllerTwo.h并声明了ViewControllerTwo:

    #import "ViewController.h"
    #import "ViewControllerTwo.h"

    @interface ViewController ()

    @end

    @implementation ViewController
    {
        ViewControllerTwo *settings;

    }
    @synthesize blockSizeLB;
    @synthesize wpmLB;
    @synthesize textTV;
    @synthesize slider;
    @synthesize stepper;
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    //sets label to corresponding value
    wpmLB.text = [NSString stringWithFormat:@"WPM: %@", [[NSNumber numberWithInt:slider.value] stringValue]];

    //configure stepper and its label to default values of 1
    stepper.value = 1;
    blockSizeLB.text = [NSString stringWithFormat:@"Block Size: %@", [[NSNumber numberWithInt:stepper.value] stringValue]];

     //sets properties for next ViewController
    settings = [[ViewControllerTwo alloc] init];
    settings.timerValue = 60 / slider.value;
    settings.text = textTV.text;
    settings.blockCount = stepper.value;



}

在ViewControllerTwo.h中我有:

@property (nonatomic) float timerValue;
@property (nonatomic) NSString * text;
@property (nonatomic) int blockCount;

稍后在ViewController.m中我需要更改ViewControllerTwo中定义的属性: ViewController.m中的方法。这也在我的viewDidLoad中提前设置属性的默认值:

- (IBAction)sliderSlide:(id)sender
{
    //event when the slider value is changed


    //rounds value to nearest increment of 5
    int increment = 5 * floor(((int)slider.value/5)+0.5);
    [slider setValue:increment animated:YES];

    //changes WPM: 0 label text
    wpmLB.text = [NSString stringWithFormat:@"WPM: %@", [[NSNumber numberWithInt:increment] stringValue]];

  //sets properties for next ViewController   
    settings.timerValue = 60 / slider.value;   
}

我尝试通过调用ViewControllerTwo.m中通过NSLog记录其属性blockCount的方法来测试这是否成功。然而输出是(null)意味着我在将数据从ViewController.m传递给ViewControllerTwo时不成功

2 个答案:

答案 0 :(得分:1)

如果您使用segues,您应该在以下内容中执行此操作:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
然后命名你的segue,然后做这样的事情:

if([segue.identifier  isEqual: @"segue_From_1_To_2"])
{
    ViewControllerTwo *vc2 = segue.destinationViewController;
    vc2.timerValue = 123.45;
    vc2.text = @"whatever";
    vc2.blockCount = 1;
}

答案 1 :(得分:-1)

您可以在viewControllerTwo中创建自定义初始值设定项。将其命名为initWithTimerValue:

- (id)initWithTimerValue:(CGFloat)timerValue
{

self = [super init];
if (self) {
self.timerValue = timerValue;
}

return self;

}