自定义委托方法仅在一个类中调用

时间:2013-06-28 20:01:28

标签: ios objective-c delegates

为什么我的委托方法只在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
}

干杯!

1 个答案:

答案 0 :(得分:0)

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