在 Objective-C 中定义和使用协议
我正在尝试扩展 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 很陌生。
I'm trying to extend NSImageView so I can delegate the drag/drop responsibility to the controller. It all works fine with the one problem that the compiler is now displaying warnings about sending messages to objects with type id. To solve this I assumed I would simply have to suffix the ivar's type with the name of the protocol. However, this fails miserably with the message that it cannot find the definition for the 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
Any pointers where I might be going wrong? I'm sure it must be something simple, but I'm quite new to obj-c.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你的方向是正确的,但你却被 C 编译器所困扰,它有点过时了。 编译器令人窒息,因为协议的定义在您使用它时不可用。 必须先定义
@protocol DragDropImageViewDelegate
才能使用id
DragDropImageViewDelegate>
作为一种类型。 您可以将@protocol 定义移到使用之前(即在@interface 之前),或者在@interface 之前添加一个(前向声明)并将@protocol 声明保留在原来的位置。
You're on the right track but you're getting hung up by the C compiler, which is a little archaic. The compiler is choking because the definition of the protocol is not available at the time you use it.
@protocol DragDropImageViewDelegate
must be defined before you can useid< DragDropImageViewDelegate>
as a type. You can move the @protocol definition before the usage (i.e. before your @interface), or add abefore the @interface (a forward declaration) and leave the @protocol declaration where it is.
作为一般规则,我首先定义协议,然后是
但是您可以执行相反的操作并在前面定义:
在我看来,协议是声明的重要组成部分,并且往往很短,所以我更喜欢它首先,而不是迷失在头文件的底部,但它是一个品味问题。
As a general rule, I define the protocol first, preceeded by
But you can do the reverse and preceed with:
To my mind, the protocol is an important part of the declaration, and tends to be quite short, so I prefer it to go first rather than be lost at the bottom of the header file, but its a matter of taste.