22

我正在尝试扩展 NSImageView 以便我可以将拖放责任委托给控制器。对于编译器现在显示有关向具有类型 id 的对象发送消息的警告的一个问题,这一切都很好。为了解决这个问题,我假设我只需在 ivar 的类型后面加上协议名称即可。但是,这会因无法找到协议定义的消息而惨遭失败。

#import <Cocoa/Cocoa.h>


@interface DragDropImageView : NSImageView {
    id <DragDropImageViewDelegate> _delegate;
}

@property (readwrite, retain) id <DragDropImageViewDelegate> delegate;

@end

@protocol DragDropImageViewDelegate

@optional

- (NSDragOperation)dragDropImageView:(DragDropImageView *)ddiv validateDrop:(id     <NSDraggingInfo>)info;
- (BOOL)dragDropImageView:(DragDropImageView *)ddiv acceptDrop:(id <NSDraggingInfo>)info;
- (void)concludeDragOperation:(id <NSDraggingInfo>)sender;  

@end

任何我可能会出错的指针?我敢肯定它一定很简单,但我对 obj-c 很陌生。

4

2 回答 2

31

你在正确的轨道上,但你被 C 编译器挂断了,这有点过时了。编译器令人窒息,因为在您使用它时协议的定义不可用。@protocol DragDropImageViewDelegate必须先定义,然后才能id< DragDropImageViewDelegate>用作类型。您可以在使用之前移动@protocol 定义(即在您的@interface 之前),或者添加一个

@protocol DragDropImageViewDelegate;

在@interface(前向声明)之前并将@protocol 声明留在原处。

于 2009-06-10T14:49:16.627 回答
10

作为一般规则,我首先定义协议,然后是

@class DragDropImageView;

但是你可以做相反的事情并继续:

@protocol DragDropImageViewDelegate;

在我看来,协议是声明的重要组成部分,而且往往很短,所以我更喜欢它先出现而不是丢失在头文件的底部,但它是一个品味问题。

于 2009-06-11T02:03:54.297 回答