How to access variable values ​​from one view controller in another?

I have an integer variable ( time ) in one view controller, the value of which I need in another view controller. Here is the code:

MediaMeterViewController

// TRP - On Touch Down event, start the timer
-(IBAction) startTimer
{
    time = 0;
    // TRP - Start a timer
    timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateTimer) userInfo:nil repeats:YES];

    [timer retain];     // TRP - Retain timer so it is not accidentally deallocated

}

// TRP - Method to update the timer display
-(void)updateTimer
{
    time++;
//  NSLog(@"Seconds: %i ", time); 
    if (NUM_SECONDS == time)
        [timer invalidate];
}

// TRP - On Touch Up Inside event, stop the timer, decide stress level, display results
-(IBAction) btn_MediaMeterResults
{
    [timer invalidate];
    NSLog(@"Seconds: %i ", time);
    ResultsViewController *resultsView = [[ResultsViewController alloc] initWithNibName:@"ResultsViewController" bundle:nil];
    [self.view addSubview:resultsView.view];
}

And in ResultsViewController I want to process the time based on its value

ResultsViewController

- (void)viewDidLoad 
{
    if(time < 3)
       {// Do something}

    else if ((time > 3) && (time < 6))
       {// Do something else}

//etc...

    [super viewDidLoad];
}

I'm a little unclear when @property and @synthesize are needed. Is this so in this situation? Any help would be greatly appreciated.

Thank! Thomas

+3
source share
1 answer

Declare timeas a property in MediaMeterViewController:

@property (nonatomic) NSInteger time;

, , , , , @synthesize ( getter setter ).

, time MediaMeterViewController self.time time. , time = 0; self.time = 0;.

time ResultsViewController, - :

- (void)viewDidLoad 
{
    [super viewDidLoad];
    if (mmvc.time < 3)
    {
        // Do something
     }

    else if ((mmvc.time > 3) && (mmvc.time < 6))
    {
    // Do something else
    }

    // etc...    
}

mmvc MediaMeterViewController. , .

+6

Source: https://habr.com/ru/post/1739215/


All Articles