从 IBAction 方法获取变量或对象



在过去的几天里,我一直在阅读,谷歌搜索和观看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);
}

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

更改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);
}

最新更新