objective-c – 如何从另一个视图控制器访问变量值?

我在一个视图控制器中有一个整数变量(时间),我在另一个视图控制器中需要它的值.这是代码

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];
}

在ResultsViewController中,我想根据其值处理时间

ResultsViewController

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

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

//etc...

    [super viewDidLoad];
}

我有点不清楚@property和@synthesize何时是必要的.在这种情况下是这样的吗?任何帮助将不胜感激.

谢谢!
托马斯

解决方法

在MediaMeterViewController中将时间声明为属性

@property (nonatomic) NSInteger time;

每当您需要访问另一个对象中的实例变量时,您应该将实例变量声明为属性,并且在声明属性时,必须始终使用@synthesize(以合成该属性的getter和setter).

另请注意,在MediaMeterViewController中设置时间时,必须始终使用self.time而不是time.例如,time = 0;应该是self.time = 0;.

要从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对象的引用.希望这可以帮助.

相关文章

在有效期内的苹果开发者账号(类型为个人或者公司账号)。还...
Appuploader官网--IOS ipa上传发布工具,证书制作工具跨平台...
苹果在9月13号凌晨(北京时间)发布 iOS 16,该系统的设备可...
计算机图形学--OpenGL递归实现光线追踪
Xcode 14打出来的包在低版本系统运行时会崩溃,报错信息是Li...