【问题标题】:Calling a method in MainViewController from custom class file从自定义类文件调用 MainViewController 中的方法
【发布时间】:2011-11-02 09:40:06
【问题描述】:

我正在使用自定义手势识别器(在链接Intercepting/Hijacking iPhone Touch Events for MKMapView 中给出)来检测 MKMapView 上的触摸事件。手势识别器在 WildcardGestureRecognizer.h 中定义并在 WildcardGestureRecognizer.m 文件中实现。当将此手势识别器添加到 MKMapview 时,可以从以下方法中读取任何触摸事件

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    if (touchesBeganCallback)
        touchesBeganCallback(touches, event);
    NSLog(@"touchesBegan");


}

基于此触摸检测,我想从 MainViewController(Containing MKMapView) 调用方法 tapMethod。

-(void) tapMethod
{
    dontUpdateLocation =1;// a variable to check stoppoing of location update.
    NSLog(@" map tapped");
}

我试过了

  - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
    {
        if (touchesBeganCallback)
            touchesBeganCallback(touches, event);
        NSLog(@"touchesBegan");
        MainViewController *updateController = [[MainViewController alloc]init ];
        [updateController tapMethod];
        [updateController release];

    }

它会打印“map tapped”,但不会更改变量 dontUpdateLocation 的值。 我该怎么做?

【问题讨论】:

  • 用什么值初始化变量dontUpdateLocation?除了tapMethod,还有什么其他方法可以修改这个变量?
  • @Mat 它被初始化为 0。没有其他方法修改这个变量。
  • NSLog(@"%i",dontUpdateLocation);NSLog(@" map tapped"); 之前呢?..dontUpdateLocation 是一个整数?
  • 是的。它是 int。我试过了,它打印出 "1","map tapped" 。但是在方法 - (void)mapView:(MKMapView *)mapView regionWillChangeAnimated:(BOOL)animated 中,当我打印 NSLog(@"will change map with %d", dontUpdateLocation);我总是得到 0。
  • 那么问题出在哪里?运行该方法后值会发生变化。为什么说不变?

标签: iphone uiviewcontroller


【解决方案1】:

根据我从您的 cmets 中了解到的情况,我认为问题出在以下事实:当您这样做时:

MainViewController *updateController = [[MainViewController alloc]init ];
[updateController tapMethod];
[updateController release];

您不是在创建对现有主视图控制器的引用,而是在创建指向内存中另一个对象的不同指针。 您可以使用 appDelegate 来存储(设置@property 和@synthesize)变量,然后像这样访问:

YourAppDelegate *appDel=(YourAppDelegate *)[[UIApplication sharedApplication] delegate];
appDel.dontUpdateLocation=1;

我建议您深入了解这些模式:SingletonsMVCDelegation

希望这会有所帮助。

【讨论】:

  • 非常感谢您的耐心等待。我使用 appDelegate 方法来存储变量,它可以按要求工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-17
  • 1970-01-01
  • 2017-06-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多