为什么我的代理为空?

3
我正在使用XCode 4.5.1构建一个iOS 6应用程序。我尝试使用协议使我的控制器可以检索图像。但是,尽管我这样调用它,但我的代理从未被调用:
UIImage *image = [self.delegate mapViewController:self imageForAnnotation:aView.annotation];

当我调试这一行时,我发现self.delegate为空,尽管我已经将TableViewController关联为它的代理。

MapViewController.h:

@class MapViewController;
@protocol MapViewControllerDelegate <NSObject>
    - (UIImage *)mapViewController:(MapViewController *)sender imageForAnnotation:(id <MKAnnotation>)annotation;
@end

@interface MapViewController : UIViewController
@property (nonatomic, weak) id <MapViewControllerDelegate> delegate;
@end

MapViewController.m:

@implementation MapViewController
@synthesize delegate = _delegate;

我正在使用TableViewController作为MapViewControllerDelegate:

@interface RecentPhotosTableViewController () <MapViewControllerDelegate>

- (PhotoViewController *) splitViewPhotoViewController;
@end

@implementation RecentPhotosTableViewController
- (UIImage *)mapViewController:(MapViewController *)sender imageForAnnotation:(id <MKAnnotation>)annotation
{
    FlickrPhotoAnnotation *fpa = (FlickrPhotoAnnotation *)annotation;
    NSURL *url = [FlickrFetcher urlForPhoto:fpa.photo format:FlickrPhotoFormatSquare];
    NSData *data = [NSData dataWithContentsOfURL:url];
    return data ? [UIImage imageWithData:data] : nil;
}

@end

2
你在哪里设置委托? - Etan
1
我看不到委托分配。 - CodaFi
3
你确实没有设置代理。顺便说一下,自 Xcode 4.4 开始,你可以省略 @synthesize delegate = _delegate; 这行代码。编译器会自动处理。 - s1m0n
2个回答

5

你的代码没有展示你将任何东西设置为其他任何东西的代理。你声明了一些属性并采用了一些协议,但这些都没有将 selfdelegate 属性实际设置为一个值。


谢谢你这么快的回复,Matt。 - seedhead

0

当然,我们并没有你所有的源代码,但是Etan和CodaFi似乎是正确的:你在哪些代码行中实例化了RecentPhotosTableViewController对象,并将该对象设置为MapViewController对象的代理?

我认为我们期望看到类似于以下内容:

@implementation RecentPhotosTableViewController

- (void) someMethod {
    self.mapViewController = [[MapViewController alloc] init];
    self.mapViewController.delegate = self;
    ...
}

在MapViewController类中声明了一个委托属性,但是在实例化后必须将该委托属性实际设置为某个对象,以使委托调用起作用。
(如果这听起来太简单了,那么似乎你遇到了相当基本的概念难题;如果我错过了重点,请原谅!)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接