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 ", 开发者_如何学JAVAtime);
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 in MediaMeterViewController
:
@property (nonatomic) NSInteger time;
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
in MediaMeterViewController
you must always use self.time
instead of time
. For example, time = 0;
should be self.time = 0;
.
To access time
from your ResultsViewController
, you would do something like this:
- (void)viewDidLoad
{
[super viewDidLoad];
if (mmvc.time < 3)
{
// Do something
}
else if ((mmvc.time > 3) && (mmvc.time < 6))
{
// Do something else
}
// etc...
}
Where mmvc
is a reference to your MediaMeterViewController
object. Hope this helps.
精彩评论