微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐