加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 01:48:32 所属栏目:百科 来源:网络整理
导读:我在一个视图控制器中有一个整数变量(时间),我在另一个视图控制器中需要它的值.这是代码: MediaMeterViewController // TRP - On Touch Down event,start the timer-(IBAction) startTimer{ time = 0; // TRP - Start a timer timer = [NSTimer scheduledTi
我在一个视图控制器中有一个整数变量(时间),我在另一个视图控制器中需要它的值.这是代码:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读