【问题标题】:ios - respondsToSelector always false with custom delegateios - 使用自定义委托时,responsToSelector 始终为 false
【发布时间】:2012-11-16 11:14:07
【问题描述】:

我在玩 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.只是为了验证,您是否首先将 MapViewController 设置为 LocationViewController 的委托?即在您的 MapViewController.m 中: self.locationViewController.delegate = self; 2. 您以 _delegate 的身份访问委托属性。验证您在 LocationViewController.m 中合成它顺便说一句,我假设您的 MapViewController 拥有一个 LocationViewController 实例,如果是这样,最好将 LocationViewController 中的委托属性设置为“弱”以避免循环引用。 @property (nonatomic, weak) id 委托;
  • 其实在我上次做的练习中,没有必要像self.locationViewController.delegate = self那样做smgt。没有这个它就可以工作。但是我只是尝试在这个例子中添加这行代码,仍然无法正常工作。是的,一切都很好合成
  • 好的,我发现问题出在哪里了。您对 locationViewController.delegate 的看法是正确的。由于我的两个控制器是 TabBarController 中的 2 个不同控制器,因此我必须在 AppDelegate 中添加 locationController.delegate = mapController
  • 好的,已经编辑了我的原始答案,所以请尽可能标记为已接受。

标签: ios delegates protocols respondstoselector


【解决方案1】:

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

self.locationViewController.delegate = self;

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-19
    • 2020-04-13
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多