我正在尝试扩展 NSImageView,这样我就可以将拖放责任委托(delegate)给 Controller 。这一切都很好地解决了一个问题,即编译器现在显示有关向具有类型 id 的对象发送消息的警告。为了解决这个问题,我假设我只需要在 ivar 的类型后面加上协议(protocol)名称作为后缀。然而,这悲惨地失败了,并显示无法找到协议(protocol)定义的消息。
#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 还很陌生。
最佳答案
您走在正确的轨道上,但您被 C 编译器挂断了,这有点过时了。编译器正在阻塞,因为协议(protocol)的定义在您使用它时不可用。 @protocol DragDropImageViewDelegate
必须先定义才能使用 id< DragDropImageViewDelegate>
作为一种类型。您可以在使用之前移动@protocol 定义(即在您的@interface 之前),或者添加一个
@protocol DragDropImageViewDelegate;
在@interface(前向声明)之前并将@protocol 声明保留在原处。
关于objective-c - 在 objective-c 中定义和使用协议(protocol),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/975888/