ios - 使用自定义委托,respondsToSelector始终为false

时间:2012-11-16 11:14:07

标签: ios delegates protocols respondstoselector

我正在玩MKMap和一些自定义委托,它不在这里工作,我真的不知道为什么:/

这是我的代码:

LocationViewController.h

#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>

@protocol LocationViewDelegate <NSObject>

@required
- (void)didReceiveLocation:(CLLocation *)location;

@end

@interface LocationViewController : UIViewController <CLLocationManagerDelegate>

@property (strong, nonatomic) IBOutlet UILabel *locationLabel;
@property (nonatomic, strong) id<LocationViewDelegate> delegate;

- (IBAction)sendLocation:(id)sender;

@end

LocationViewController.m

[...]
- (IBAction)sendLocation:(id)sender {
    if ([_delegate respondsToSelector:@selector(didReceiveLocation:)]) {
        [_delegate didReceiveLocation:_currentLocation];
    } else {
        NSLog(@"nope");
    }
}
[...]

MapViewController.h

#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#import "LocationViewController.h"

@interface MapViewController : UIViewController <LocationViewDelegate>

@end

MapViewController.m

[...]
- (void)didReceiveLocation:(CLLocation *)location {
    _mapView.centerCoordinate = location.coordinate;
}
[...]

我总是收到“nope”消息意味着respondsToSelector返回NO。 几天前我做了相同的例子,一切都很好。

有人可以看到这里的问题在哪里?

1 个答案:

答案 0 :(得分:4)

将MapViewController设置为LocationViewController的委托,即在MapViewController.m中:

self.locationViewController.delegate = self;

除此之外,我假设您的MapViewController拥有一个LocationViewController实例,如果是这样,最好将LocationViewController中的delegate属性设置为'weak'以避免循环引用。 @property(非原子,弱)id委托;