I have an integer variable (time) in one view controller whose value I need in another view controller. Here's 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 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 kind of unclear on when @property and @synthesize is necessary. Is that the case in this situation? Any help would be greatly appreciated.
Thanks! Thomas
Declare
time
as a property inMediaMeterViewController
:Whenever you need to access an instance variable in another object, you should have the instance variable declared as a property, and when you declare a property you must always use
@synthesize
(to synthesize the getter and setter for that property).Also take note that when setting
time
inMediaMeterViewController
you must always useself.time
instead oftime
. For example,time = 0;
should beself.time = 0;
.To access
time
from yourResultsViewController
, you would do something like this:Where
mmvc
is a reference to yourMediaMeterViewController
object. Hope this helps.