【问题标题】:Get variable or object from IBAction method从 IBAction 方法获取变量或对象
【发布时间】:2012-11-06 20:45:54
【问题描述】:

在过去的几天里,我一直在阅读、谷歌搜索和观看 Lynda 的视频来寻找答案。我还没有找到好的答案。

这看起来应该很简单。使用普通方法,我可以传递变量。但是由于 IBAction 为(无效),我无法弄清楚如何将变量传递给另一种方法。

以下是我想做的一些简单示例:

- (IBAction)treeButton:(id)sender {
    int test = 10;
}


-(void)myMethod{
     NSLog(@"the value of test is %i",test);
}

这是我真正想要的工作。我试图让一个按钮设置我想要存储并以另一种方法使用的初始位置。

- (IBAction)locationButton:(id)sender {
    CLLocation *loc1 = [[CLLocation alloc]
       initWithLatitude:_locationManager.location.coordinate.latitude
       longitude:_locationManager.location.coordinate.longitude];
}


-(void)myMethod{
     NSLog(@"the value of test is %i",test);
     NSLog(@"location 1 is %@",loc1);
}

任何能引导我走向正确方向的建议都会很棒。我已经阅读并观看了有关变量范围、实例变量等的视频。只是不明白我需要在这里做什么

【问题讨论】:

  • 也许再看一个实例变量视频? loc1 需要是一个实例变量,目前它的范围仅限于您的方法。
  • 在您的控制器中创建一个新的实例变量,即 loc1,并在每次触发某个 IBAction 并从其他方法使用它时为其分配一个值。就这么简单。
  • 感谢您的帮助。 esqew 的回答告诉我,我正在我的方法中重新定义实例变量。猜猜这很容易。

标签: iphone ios xcode ipad ios6


【解决方案1】:

更改myMethod 以接受您需要的参数:

- (void)myMethod:(CLLocation *)location {
    NSLog(@"location 1 is %@", location);
}

像这样调用它:

- (IBAction)locationButton:(id)sender {
    CLLocation *loc1 = [[CLLocation alloc]
       initWithLatitude:_locationManager.location.coordinate.latitude
       longitude:_locationManager.location.coordinate.longitude];
    [self myMethod:loc1];
}

如果您需要通过多种方法或在代码中的不同位置访问它,我建议在您的 @interface 声明中为 loc1 创建一个实例变量。

@interface MyClass : NSObject {
    CLLocation *loc1;
}

在您的方法中,您只需设置它,而不是重新声明它:

loc1 = [[CLLocation alloc]
       initWithLatitude:_locationManager.location.coordinate.latitude
       longitude:_locationManager.location.coordinate.longitude];

myMethod,只需访问它:

- (void)myMethod{
    NSLog(@"location 1 is %@", loc1);
}

【讨论】:

  • 感谢您快速简洁的回答。在在这里提出问题之前,我花了 3 天时间试图弄清楚这一点(学到了很多东西)。我没有意识到我在我的方法中重新声明了实例变量。现在完全有道理。谢谢!!!
猜你喜欢
  • 2011-07-30
  • 2018-07-23
  • 2021-12-01
  • 2011-01-01
  • 1970-01-01
  • 2011-02-23
  • 1970-01-01
  • 1970-01-01
  • 2013-04-13
相关资源
最近更新 更多