0

好吧,所以我想通过下面的代码将数据从一个视图控制器传递到另一个,但它不工作,我不知道为什么。通过ViewControllers传递数据不工作

在我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的方法,它记录其财产blockCount通过NSLog的成功。但是输出是意味着我是在从ViewController.m传递数据给ViewControllerTwo

+1

你在哪里初始化'settings'变量指向一个实际的'ViewControllerTwo'对象? –

+0

我更新了它,以包含我的viewDidLoad方法。难道是因为Im在ViewControllerTwo.m中合成之前将值设置为属性? – user2692560

+0

我怀疑您创建的'ViewControllerTwo'实例是否与您正在测试的实例相同。如果你在给它赋值的时候记录'settings'的值,当'ViewControllerTwo'打印它的'blockCount'时记录'self'的值,它们是否显示相同的地址? –

回答

1

如果您正在使用塞格斯,你应该这样做的内部:
- (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

您可以创建一个在您viewControllerTwo自定义初始化不成功的(空)。它命名为initWithTimerValue:

- (id)initWithTimerValue:(CGFloat)timerValue 
{ 

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

return self; 

}