【发布时间】: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