1

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

这是我的代码:

位置视图控制器.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

位置视图控制器.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。几天前我做了同样的例子,一切都很好。

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

4

1 回答 1

4

将您的 MapViewController 设置为 LocationViewController 的代表,即在您的 MapViewController.m 中:

self.locationViewController.delegate = self;

顺便说一句,我假设您的 MapViewController 拥有一个 LocationViewController 实例,如果是这样,最好将 LocationViewController 中的委托属性设置为“弱”以避免循环引用。@property (nonatomic, weak) id 代表;

于 2012-11-22T18:22:35.100 回答