【问题标题】:custom delegate method only gets called in one class自定义委托方法只在一个类中被调用
【发布时间】:2013-06-28 20:01:27
【问题描述】:

为什么我的委托方法只在 MainViewController 中调用,而不在 MapViewController 中调用?

LocationService.h

@protocol LocationServiceDelegate <NSObject>
@optional
- (void) currentLocation: (CLLocation*) location;
@end

@property (nonatomic, assign) id delegate;

LocationService.m

if ([delegate respondsToSelector:@selector(currentLocation:)])
{
    [delegate currentLocation:newLocation];
}

这里方法被调用(在 MainViewController 中)

MainViewController.h

#import "LocationService.h"
@interface MainViewController : UIViewController <LocationServiceDelegate>

MainViewController.m

locationService = [[LocationService alloc] init];
locationService.delegate = self;

- (void) currentLocation: (CLLocation*) location
{
    // some code, this method get called perfectly
}

在我的另一堂课中,同样的程序不会起作用

MapViewController.h

#import "LocationService.h"
@interface MapViewController : UIViewController <MKMapViewDelegate, LocationServiceDelegate>

MapViewController.m

- (void)viewDidLoad
{
    [super viewDidLoad];
    locationService =[[LocationService alloc] init];

    locationService.delegate = self;
}


- (void)currentLocation:(CLLocation *)location
{
  // this method does not get called
}

干杯!

【问题讨论】:

  • 在此处添加断点if ([delegate respondsToSelector:@selector(currentLocation:)]) 并逐步执行。
  • MapViewController 的视图是否真的被加载了?我的意思是,第二个 viewDidLoad 方法是否被调用过?
  • @ludesign: 如果我这样做,我只会在 MainViewController.m 中的- (void) currentLocation: (CLLocation*) location 中加入
  • @AaronGolden 是的 viewDidLoad 被调用
  • 这很奇怪。你的代码中的其他东西让你很棘手。在您的 LocationService 方法(init 和其他方法)上放置断点,看看发生了什么;或给我们更多代码,以便我们为您提供更多帮助。

标签: ios objective-c delegates


【解决方案1】:

您是否在某处将委托设置为 nil,因为我的代码看起来不错?请使用 break 指针查看它是否进入 MapViewController 中的 currentLocation 方法实现。

【讨论】:

  • 感谢您的回答,但正如我上面提到的,我已经在使用断点了
  • 很难看到您发布的代码似乎很好,因此信息有限。
  • 您能发布一下您是如何为 LocationService 定义委托的吗?
  • 我在 LocationService.h 中编辑了我的代码,你可以看到我如何将委托定义为属性
  • 根据给定的信息,我看不出代码有什么问题。
猜你喜欢
  • 2015-10-02
  • 2017-03-31
  • 2014-11-02
  • 2013-02-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多